将3D Numpy阵列重塑为2D阵列
问题描述:
我在Numpy中具有以下3D阵列:
I have the following 3D array in Numpy:
a = np.array([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]],[[13,14],[15,16]]])
我写
b = np.reshape(a, [4,4])
二维结果数组将类似于
[[ 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]]
如何在Python/Numpy中高效地做到这一点?
How can I do this efficiently in 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)
样品运行-
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]])