concatenate numpy arrays which are elements of a list

Question:

I have a list containing numpy arrays something like L=[a,b,c] where a, b and c are numpy arrays with sizes N_a in T, N_b in T and N_c in T.
I want to row-wise concatenate a, b and c and get a numpy array with shape (N_a+N_b+N_c, T). Clearly one solution is run a for loop and use numpy.concatenate, but is there any pythonic way to do this?

Thanks

Asked By: TNM

||

Answers:

Use numpy.vstack.

L = (a,b,c)
arr = np.vstack(L)
Answered By: shx2

help('concatenate' has this signature:

concatenate(...)
    concatenate((a1, a2, ...), axis=0)

    Join a sequence of arrays together.

(a1, a2, ...) looks like your list, doesn’t it? And the default axis is the one you want to join. So lets try it:

In [149]: L = [np.ones((3,2)), np.zeros((2,2)), np.ones((4,2))]

In [150]: np.concatenate(L)
Out[150]: 
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 0.,  0.],
       [ 0.,  0.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])

vstack also does this, but look at its code:

def vstack(tup):
    return np.concatenate([atleast_2d(_m) for _m in tup], 0)

All it does extra is make sure that the component arrays have 2 dimensions, which yours do.

Answered By: hpaulj
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.