繁体   English   中英

将numpy 3D数组重塑为2D

[英]reshape numpy 3D array to 2D

我有一个很大的数组,形状为((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]])

您可以使用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]])

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]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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