简体   繁体   English

将3D Numpy阵列重塑为2D阵列

[英]Reshaping 3D Numpy Array to a 2D array

I have the following 3D array in Numpy: 我在Numpy中具有以下3D阵列:

a = np.array([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]],[[13,14],[15,16]]])

when I write 当我写

b = np.reshape(a, [4,4])

The 2D resulting array will look like 二维结果数组看起来像

 [[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]
  [13 14 15 16]]

However, I want it to be in this shape: 但是,我希望它具有以下形状:

 [[ 1  2  5  6]
  [ 3  4  7  8]
  [ 9 10 13 14]
  [11 12 15 16]]

How can I do this efficiently in Python/Numpy? 如何在Python / Numpy中有效地做到这一点?

Reshape to split the first axis into two, permute axes and one more reshape - 重新塑形以将第一根轴拆分为两个置换轴,再进行一次塑形-

a.reshape(2,2,2,2).transpose(0,2,1,3).reshape(4,4)
a.reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)

Making it generic, would become - 使其通用,将成为-

m,n,r = a.shape
out = a.reshape(m//2,2,n,r).swapaxes(1,2).reshape(-1,2*r)

Sample run - 样品运行-

In [20]: a
Out[20]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]],

       [[13, 14],
        [15, 16]]])

In [21]: a.reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)
Out[21]: 
array([[ 1,  2,  5,  6],
       [ 3,  4,  7,  8],
       [ 9, 10, 13, 14],
       [11, 12, 15, 16]])

Another approach using just np.hstack and np.vstack : 仅使用np.hstacknp.vstack另一种方法:

In [98]: a
Out[98]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]],

       [[13, 14],
        [15, 16]]])

In [99]: s0, s1, s2, s3 = range(a.shape[0])

In [100]: np.vstack((np.hstack((a[s0], a[s1])), np.hstack((a[s2], a[s3]))))
Out[100]: 
array([[ 1,  2,  5,  6],
       [ 3,  4,  7,  8],
       [ 9, 10, 13, 14],
       [11, 12, 15, 16]])

Realizing the fact that your aim is to squash the first two slices of your original array into one slice and the next two into another slice and so on. 意识到您的目标是将原始数组的前两个切片压缩为一个切片,然后将第二个切片压缩为另一个切片,依此类推。

And you could also just replace the np.vstack and np.hstack with their fastest cousin np.concatenate , if you're concerned about performance. 如果您担心性能,也可以用最快的表亲np.concatenate替换np.vstacknp.hstack

PS: This approach creates a new array leaving your original one unchanged. PS:这种方法会创建一个新数组,而原来的数组保持不变。

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

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