I created a sample array:
a = np.arange(18).reshape(9,2)
On printing, I get this as output:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
On executing this reshaping:
b = a.reshape(2,3,3).swapaxes(0,2)
I get:
[[[ 0 9]
[ 3 12]
[ 6 15]]
[[ 1 10]
[ 4 13]
[ 7 16]]
[[ 2 11]
[ 5 14]
[ 8 17]]]
I went through this question, but it does not solve my problem.
The documentation is not useful either.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html
I need to know how the swapping is working(which is x-axis, y-axis, z-axis). A diagrammatic explanation would be most helpful.
Start with the reshape
This displays as 2 planes, and each plane is a 3x3. Is that part clear? The fact that the array was shaped (9,2) at one point isn't significant. Reshaping doesn't change the order of elements.
Apply the
swapaxes
. Shape is now (3,3,2). 3 planes, each is 3x2. This particular swap is the same as a transposeThe middle axis is unchanged. There are still columns of [0,3,6], [9,12,15], etc.
It may be easier to visualize the change with 3 different sized axes
Notice what happens when I flatten the array
the order of terms has been shuffled. As created it was [0,1,2,3...]. Now the
1
is the 6th term (2x3).Under the covers
numpy
actually performs the swap or transpose by changingshape
,strides
andorder
, without changing the data buffer (i.e. it's a view). But further reshaping, including raveling, forces it to make a copy. But that might be more confusing than helpful at this stage.In
numpy
axes are numbered. Terms like x,y,z or planes, rows, columns may help you map those on to constructs that you can visualize, but they aren't 'built-in'. Describing the swap or transpose in words is tricky.Here is my understanding of
swapaxes
Suppose you have an array
And the shape of
arr
is(2, 2, 4)
, for the value7
, you can get the value byThere are 3 axes 0, 1 and 2, now, we swap axis 0 and 2
And as you can guess, the index of
7
is(3, 1, 0)
, with axis1
unchanged,So, now from the perspective of the index, swapping axis is just change the index of values. For example
So, if you feel difficult to get the swapped-axis array, just change the index, say
arr_swap[2, 1, 0] = arr[0, 1, 2]
.