numpy的transpose方法可以很方便地调换多维数组的轴。
1 import numpy as np
2 a = np.arange(0, 32).reshape((2,4,4))
3 print(a)
输出:
[[[ 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 30 31]]]
现在把axis 0和1调换:
1 a.transpose(1,0,2)
输出:
array([[[ 0, 1, 2, 3],
[16, 17, 18, 19]],
[[ 4, 5, 6, 7],
[20, 21, 22, 23]],
[[ 8, 9, 10, 11],
[24, 25, 26, 27]],
[[12, 13, 14, 15],
[28, 29, 30, 31]]])