将numpy 3D数组重塑为2D

时间:2016-02-18 00:37:30

标签: python arrays numpy

我有一个非常大的数组,其形状=(32,3,1e6) 我需要将它重塑为这个形状=(3,32e6)

在一个片段中,如何从这个::

开始
>>> m3_3_5
array([[[8, 4, 1, 0, 0],
        [6, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[8, 7, 1, 0, 3],
        [2, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[2, 4, 0, 2, 3],
        [2, 5, 5, 3, 2],
        [1, 1, 1, 1, 1]]])

到这个::

>>> res3_15
array([[8, 4, 1, 0, 0, 8, 7, 1, 0, 3, 2, 4, 0, 2, 3],
       [6, 8, 5, 5, 2, 2, 8, 5, 5, 2, 2, 5, 5, 3, 2],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

我确实尝试过使用重塑的各种组合但没有成功::

>>> dd.T.reshape(3, 15)
array([[8, 8, 2, 6, 2, 2, 1, 1, 1, 4, 7, 4, 8, 8, 5],
       [1, 1, 1, 1, 1, 0, 5, 5, 5, 1, 1, 1, 0, 0, 2],
       [5, 5, 3, 1, 1, 1, 0, 3, 3, 2, 2, 2, 1, 1, 1]])

>>> dd.reshape(15, 3).T.reshape(3, 15)
array([[8, 0, 8, 2, 1, 8, 0, 8, 2, 1, 2, 2, 5, 2, 1],
       [4, 0, 5, 1, 1, 7, 3, 5, 1, 1, 4, 3, 5, 1, 1],
       [1, 6, 5, 1, 1, 1, 2, 5, 1, 1, 0, 2, 3, 1, 1]])

2 个答案:

答案 0 :(得分:3)

您可以使用np.hstack

获得所需的行为
# g is your (3,3,5) array from above
reshaped = np.hstack(g[i,:,:] for i in range(3))  #uses a generator exp
reshaped_simpler = np.hstack(g) # this produces equivalent output to the above statmement
print reshaped # (3,30)

输出

array([[8, 4, 1, 0, 0, 8, 7, 1, 0, 3, 2, 4, 0, 2, 3],
       [6, 8, 5, 5, 2, 2, 8, 5, 5, 2, 2, 5, 5, 3, 2],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

答案 1 :(得分:2)

a.transpose([1,0,2]).reshape(3,15)会做你想要的。 (我基本上是关注@hpaulj的评论)。

In [14]: a = np.array([[[8, 4, 1, 0, 0],
        [6, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[8, 7, 1, 0, 3],
        [2, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[2, 4, 0, 2, 3],
        [2, 5, 5, 3, 2],
        [1, 1, 1, 1, 1]]])

In [15]: a.transpose([1,0,2]).reshape(3,15)
Out[15]: 
array([[8, 4, 1, 0, 0, 8, 7, 1, 0, 3, 2, 4, 0, 2, 3],
       [6, 8, 5, 5, 2, 2, 8, 5, 5, 2, 2, 5, 5, 3, 2],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])