[英]Numpy reshaping 2D to 3D: moving columns to "depth"
题
如何将 2D 矩阵重塑为 3D 矩阵,其中列在“深度方向”移动?
我希望数组 a 看起来像数组 b
import numpy as np
a = np.array([
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
])
b = np.array([
[[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1]],
[[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2]],
[[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3]],
])
我试图做的
结果不是我想要达到的结果
x = np.reshape(a, (a.shape[0], -1, 3))
我还尝试了以下操作:1)将 a 分成 3 组 2)尝试对这些组进行 dstack 但没有产生想要的结果
b = np.hsplit(a,3)
c = np.dstack([b[0],b[1],b[2]])
这应该做:
import numpy as np
a = np.array([
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
])
b = np.array([
[[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1]],
[[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2]],
[[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3]],
])
a_new = np.swapaxes(a.reshape(a.shape[0], 3, -1), 0, 1)
np.array_equal(a_new, b)
-> 真
你只需要transpose
T
并reshape
a.T.reshape(3,4,6)
或者
a.T.reshape(b.shape)
Out[246]:
array([[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]],
[[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2]],
[[3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.