[英]How to transpose a 3D matrix?
I have a 3D matrix x_test
of size (100, 33, 66)
and I want to change its dimensions to (100, 66, 33)
.我有一个大小为
(100, 33, 66)
的 3D 矩阵x_test
,我想将其尺寸更改为(100, 66, 33)
。
What is the most efficient way to do this using python3.5?使用 python3.5 执行此操作的最有效方法是什么? I look for something along those lines:
我在这些方面寻找一些东西:
y = x_test.transpose()
You can pass the desired dimensions to the function np.transpose
using in your case np.transpose(x_test, (0, 2, 1))
.您可以在您的情况下使用
np.transpose(x_test, (0, 2, 1))
将所需的尺寸传递给函数np.transpose
。
For example,例如,
import numpy as np
x_test = np.arange(30).reshape(3, 2, 5)
print(x_test)
print(x_test.shape)
This will print这将打印
[[[ 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)
Now, you can transpose the matrix with the command from above现在,您可以使用上面的命令转置矩阵
y = np.transpose(x_test, (0, 2, 1))
print(y)
print(y.shape)
which will give这会给
[[[ 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)
Apart from transpose
(see @Cleb's answer) there are also swapaxes
and moveaxis
:除了
transpose
(参见@Cleb 的回答)之外,还有swapaxes
和moveaxis
:
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]]])
np.rot90 is another option. np.rot90 是另一种选择。 I confess I do not yet understand the axes = (a, b) notation and sort through all combinations from (0, 1) to (2, 1) to find what I want.
我承认我还不理解轴 = (a, b) 表示法并从 (0, 1) 到 (2, 1) 的所有组合中进行排序以找到我想要的。 Using x_test above, note its original shape (3, 2 ,5):
使用上面的 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.