我有一个像这样的3D数组:
[[[ 0 0 1 0 -1 1 1 0 0]
[ 0 0 -1 0 1 -1 -1 0 0]
[ 0 0 1 -2 -1 1 0 0 0]
[ 0 0 -1 2 1 -1 0 0 0]]
[[ 0 0 0 2 0 0 1 0 0]
[ 0 0 0 0 0 0 0 0 0]
[ 0 0 0 -2 0 0 -1 0 0]
[ 0 0 0 0 0 0 0 0 0]]
[[ 0 0 1 0 -1 1 1 0 0]
[ 0 0 -1 2 1 -1 0 0 0]
[ 0 0 1 -2 -1 1 0 0 0]
[ 0 0 -1 0 1 -1 -1 0 0]]
[[ 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0]]]
我需要对其进行整形,以便每个矩阵中的所有第一行在矩阵中组合在一起,然后是所有第二行,等等。
结果如下:
[[[ 0 0 1 0 -1 1 1 0 0]
[ 0 0 0 2 0 0 1 0 0]
[ 0 0 1 0 -1 1 1 0 0]
[ 0 0 0 0 0 0 0 0 0]]
[[ 0 0 -1 0 1 -1 -1 0 0]
[ 0 0 0 0 0 0 0 0 0]
[ 0 0 -1 2 1 -1 0 0 0]
[ 0 0 0 0 0 0 0 0 0]]
[[ 0 0 1 -2 -1 1 0 0 0]
[ 0 0 0 -2 0 0 -1 0 0]
[ 0 0 1 -2 -1 1 0 0 0]
[ 0 0 0 0 0 0 0 0 0]]
[[ 0 0 -1 2 1 -1 0 0 0]
[ 0 0 0 0 0 0 0 0 0]
[ 0 0 -1 0 1 -1 -1 0 0]
[ 0 0 0 0 0 0 0 0 0]]]
答案 0 :(得分:5)
您只需要swap the first two axes数组x
。如果数组是ndarray
(就像你的那样),则返回一个视图,不会复制任何数据:
>>> x.swapaxes(0,1)
例如:
>>> x = np.arange(27).reshape(3,3,3)
>>> x
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
>>> x.swapaxes(0,1)
array([[[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20]],
[[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23]],
[[ 6, 7, 8],
[15, 16, 17],
[24, 25, 26]]])