Difficulty understanding .moveaxis in Numpy - Printable Version +- Python Forum ( https://python-forum.io)+-- Forum: Python Coding ( https://python-forum.io/forum-7.html)+--- Forum: General Coding Help ( https://python-forum.io/forum-8.html)+--- Thread: Difficulty understanding .moveaxis in Numpy ( /thread-42539.html) |

Difficulty understanding .moveaxis in Numpy - leea2024 - Aug-05-2024
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. 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. 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. 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? If axis 0 is now moved to the last place, shouldn't the system fill up the array along axis 0 first?
RE: Difficulty understanding .moveaxis in Numpy - Gribouillis - Aug-05-2024
Let us call the original axes A B C instead of 0, 1, 2. Initially - moving along axis A changes page: 0 -> 12 (slow axis)
- moving along axis B changes row: 0 -> 4
- moving along axis C changes element: 0 -> 1 (fast axis)
- page changes along axis B: 0 -> 4 (now the slow axis)
- row changes along axis C: 0 -> 1
- element changes along axis A: 0-> 12 (now the fast axis)
An experiment >>> import numpy as np >>> a=np.arange(24).reshape(2,3,4) >>> b = np.moveaxis(a, 0, 2) >>> for i in range(2): ... for j in range(3): ... for k in range(4): ... assert a[i][j][k] == b[j][k][i] ... >>> RE: Difficulty understanding .moveaxis in Numpy - leea2024 - Aug-10-2024
(Aug-05-2024, 04:40 PM)Gribouillis Wrote: Let us call the original axes A B C instead of 0, 1, 2. Initially This is very clear. Thank you for your explanation! |