如何转置一个3D矩阵?

12

我有一个大小为(100, 33, 66)的3D矩阵x_test,我想将其维度改为(100, 66, 33)

在使用Python3.5时,最有效的方法是什么? 我正在寻找类似以下代码的方法:

y = x_test.transpose()
3个回答

18
你可以在函数np.transpose中传入所需的维度,对于你的情况使用np.transpose(x_test, (0, 2, 1))

例如,

import numpy as np

x_test = np.arange(30).reshape(3, 2, 5)

print(x_test)
print(x_test.shape)

这将打印

[[[ 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 27 28 29]]]
(3, 2, 5)

现在,您可以使用上面的命令转置矩阵

y = np.transpose(x_test, (0, 2, 1))
print(y)
print(y.shape)

这将提供

[[[ 0  5]
  [ 1  6]
  [ 2  7]
  [ 3  8]
  [ 4  9]]

 [[10 15]
  [11 16]
  [12 17]
  [13 18]
  [14 19]]

 [[20 25]
  [21 26]
  [22 27]
  [23 28]
  [24 29]]]
(3, 5, 2)

5
除了@Cleb的回答中提到的transpose之外,还有swapaxesmoveaxis:
import numpy as np
mock = np.arange(30).reshape(2,3,5)

mock.swapaxes(1,2)
# array([[[ 0,  5, 10],
    [ 1,  6, 11],
    [ 2,  7, 12],
    [ 3,  8, 13],
    [ 4,  9, 14]],

   [[15, 20, 25],
    [16, 21, 26],
    [17, 22, 27],
    [18, 23, 28],
    [19, 24, 29]]])
np.moveaxis(mock,2,1)
# array([[[ 0,  5, 10],
    [ 1,  6, 11],
    [ 2,  7, 12],
    [ 3,  8, 13],
    [ 4,  9, 14]],

   [[15, 20, 25],
    [16, 21, 26],
    [17, 22, 27],
    [18, 23, 28],
    [19, 24, 29]]])

0

np.rot90是另一种选择。我承认我还不理解axes =(a,b)符号表示什么,所以我会从(0,1)到(2,1)的所有组合中进行排序,以找到我想要的结果。使用上面的x_test,请注意其原始形状为(3,2,5):

x2 = np.rot90(x_test, axes = (0, 1))

array([[[ 5,  6,  7,  8,  9],
    [15, 16, 17, 18, 19],
    [25, 26, 27, 28, 29]],

   [[ 0,  1,  2,  3,  4],
    [10, 11, 12, 13, 14],
    [20, 21, 22, 23, 24]]])

x2.shape
(2, 3, 5)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接