简体   繁体   中英

numpy stack rows of ndarray

I have a ndarray A of shape (u,v,w) like this:

  [[[ 1.,  1.,  0.],
    [ 1.,  3.,  0.]],

   [[ 0.,  0.,  0.],
    [ 0.,  0.,  0.]]]

I need to stack the rows (along dimension 0) together like so.

[[1.,   1.,   0.,   0.,   0.,   0.],
 [1.,   3.,   0.,   0.,   0.,   0.]]

How do I do this? I know that if there are only two rows I can do np.hstack((a[0], a[1])) but is there any way to do this without converting the rows into a tuple? I want to use this code in theano (because numpy and theano work similarly)

This shoul work fine:

np.hstack(a)

Btw a[0], a[1], ... are the rows and not columns of a .

All the concatenate family of functions iterate over the argument, whether it's a list, tuple or array

In [318]: x=np.arange(12).reshape(2,2,3)

In [319]: x
Out[319]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

These all equivalent:

In [320]: np.hstack([x[0],x[1]])
Out[320]: 
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11]])

In [321]: np.hstack(x)
Out[321]: 
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11]])

In [322]: np.concatenate([x1 for x1 in x],axis=1)
Out[322]: 
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11]])

In [323]: np.concatenate(x,axis=1)
Out[323]: 
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11]])

Reshape can produce an array of the right shape, but the wrong order:

In [332]: x.reshape(2,6)
Out[332]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])

but if we swap the 1st 2 axes first, reshape works:

In [333]: x.transpose(1,0,2).reshape(2,6)
Out[333]: 
array([[ 0,  1,  2,  6,  7,  8],
       [ 3,  4,  5,  9, 10, 11]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM