如何在 .transpose 之后转置轴?

How to transpose axes back after .transpose?

我想知道如何撤消转置操作。让我更具体地举个例子:

a = np.random.rand(25,32,11) 
b = a.transpose(2,0,1)
c = b.transpose(??) ### Here I should set (1,0,2) 
# c == a

我应该在最后一个转置中设置哪些值才能使 c == a ?我猜在 numpy 中没有像“transpose_undo”这样的方法。 作为一种解决方案,我们可以依赖阵列的实际形状,但我们可以在未来拥有 25x25x25 阵列...

使用转置,按照顺序来就行了。您的第一个排列映射维度为:

0th transformed is 2nd original
1st transformed is 0th original
2nd transformed is 1st original
-------------------
0th original is 1st transformed
1st original is 2nd transformed
2nd original is 0th transformed
a = np.random.rand(25,32,11) 
b = a.transpose(2,0,1)
np.all(a == b.transpose(1, 2, 0))

产量true

编辑:

如果你想自动逆排列你可以使用np.argsort

axes = [2, 0, 1]
b = a.transpose(*axes)
np.all(a == b.transpose(*np.argsort(axes))  # yields true