如何转置3D矩阵?

时间:2017-11-24 09:58:15

标签: python python-3.x numpy matrix transpose

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

使用python3.5执行此操作的最有效方法是什么?我在这些方面寻找一些东西:

y = x_test.transpose()

2 个答案:

答案 0 :(得分:13)

您可以在案例np.transpose(x_test, (0, 2, 1))中使用所需的维度np.transpose

例如,

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)

答案 1 :(得分:5)

除了transpose(请参阅@ Cleb'答案)之外,还有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]]])