gpt4 book ai didi

python - 重新排列 3D 数组的行

转载 作者:行者123 更新时间:2023-11-28 21:52:53 24 4
gpt4 key购买 nike

我有一个像这样的值的 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]]]

我需要 reshape 它,以便每个矩阵中的所有第一行都组合在一个矩阵中,然后是所有第二行,依此类推。

所以结果看起来像:

[[[ 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]]]

最佳答案

你只需要 swap the first two axes你的数组 x。如果数组是 ndarray(如您的数组),则返回一个 View 并且不复制任何数据:

>>> 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]]])

关于python - 重新排列 3D 数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com