I am learning Numpy in Python. I am having difficulties understanding .moveaxis
in Numpy.
I first create an array by using a=np.arange(24).reshape(2,3,4)
. The system will first fill up axis 2 with 0 1 2 3
, then move along axis 1 to the next row. When the first ‘page’ is done, the system move along axis 0. The following is obtained.
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]]])
If I input b = np.swapaxes(a,0,2); b
now, the system should fill up axis 0 first, then axis 1 and finally axis 2. The following is obtained.
array([[[ 0, 12],
[ 4, 16],
[ 8, 20]],
[[ 1, 13],
[ 5, 17],
[ 9, 21]],
[[ 2, 14],
[ 6, 18],
[10, 22]],
[[ 3, 15],
[ 7, 19],
[11, 23]]])
This is understandable as axis 1 is preserved, so we can still see columns like 0 4 8
and 1 5 9
after swapping the axes.
But I don’t really understand how .moveaxis
works. If I input b = np.moveaxis(a,0,2); b
, the following is obtained.
array([[[ 0, 12],
[ 1, 13],
[ 2, 14],
[ 3, 15]],
[[ 4, 16],
[ 5, 17],
[ 6, 18],
[ 7, 19]],
[[ 8, 20],
[ 9, 21],
[10, 22],
[11, 23]]])
I know that the .moveaxis
function is meant to ‘move axis 0 to a new position while the other axes remain the same order’, but what is the meaning of that? I understand that the result should be an array with shape (3, 4, 2)
, but why would the system go down the first column in the first place then move on to the second page? Any help on understanding the mechanism behind .moveaxis
is appreciated.