Python Numpy将二维重塑为三维:将列移动到;“深度”;
问题 如何将二维矩阵重塑为三维矩阵,其中列将“按深度”移动 我希望数组a看起来像数组bPython Numpy将二维重塑为三维:将列移动到;“深度”;,python,numpy,3d,2d,reshape,Python,Numpy,3d,2d,Reshape,问题 如何将二维矩阵重塑为三维矩阵,其中列将“按深度”移动 我希望数组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],
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) 试图对这些集合进行数据堆栈,但未产生想要的结果
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)
->真的您只需要
转置
,即T
和重塑
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]]])