重新排序3D阵列的行

重新排序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]]]

最佳答案

你只需要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]]])

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

10-10 14:11