我有一个表示矩阵的数组数组,我需要转置每个矩阵,理想情况下不需要在循环中进行转置。当我使用array.T时,它会转换所有内容,而不仅仅是每个数组中的轴。是否可以只转换每个矩阵?
INPUT: np.arange(27).reshape(3, 3, 3).T
OUTPUT:
[[[ 0 9 18]
[ 3 12 21]
[ 6 15 24]]
[[ 1 10 19]
[ 4 13 22]
[ 7 16 25]]
[[ 2 11 20]
[ 5 14 23]
[ 8 17 26]]]
我想要的是阵列看起来像这样:
[[[ 0 3 6]
[ 1 4 7]
[ 2 5 8]]
[[ 9 12 15]
[ 10 13 16]
[ 11 14 17]]
[[ 18 21 24]
[ 19 22 25]
[ 20 23 26]]]
答案 0 :(得分:0)
In [11]: A = np.arange(27).reshape(3, 3, 3)
In [12]: A
Out[12]:
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]]])
转置最后两个维度:
In [13]: A.transpose(0,2,1)
Out[13]:
array([[[ 0, 3, 6],
[ 1, 4, 7],
[ 2, 5, 8]],
[[ 9, 12, 15],
[10, 13, 16],
[11, 14, 17]],
[[18, 21, 24],
[19, 22, 25],
[20, 23, 26]]])
A.swapaxes(1,2)
也可以。