Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate numpy arrays which are elements of a list

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

like image 891
TNM Avatar asked Jan 24 '15 12:01

TNM


2 Answers

Use numpy.vstack.

L = (a,b,c)
arr = np.vstack(L)
like image 151
shx2 Avatar answered Oct 08 '22 20:10

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.

like image 26
hpaulj Avatar answered Oct 08 '22 19:10

hpaulj