concatenate numpy arrays which are elements of a list

55,111

Solution 1

Use numpy.vstack.

L = (a,b,c)
arr = np.vstack(L)

Solution 2

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.

Share:
55,111
TNM
Author by

TNM

Updated on January 25, 2020

Comments

  • TNM
    TNM over 4 years

    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

  • TNM
    TNM over 9 years
    I see. So essentially, it should be faster to use concatenate here. Thanks
  • hpaulj
    hpaulj over 9 years
    vstack shouldn't add much time, since it is just fiddling with properties like shape and strides. Basically it's a convenience function.