pierre_j
pierre_j

Reputation: 983

Numpy / Uncertain about equivalence between np.swapaxes(array, 1,2) and np.swapaxes(array, 2,1)?

I am not so at ease with use of np.swapaxes and set aside my proudness to ask this possibly silly question.

Is it normal that considering a 3D array (for instance (2, 4, 3)), np.swapaxes(array, 1,2) gives same result than np.swapaxes(array, 2,1)?

array = np.array([[[1.0, -1.0, -2.0],[-1.0, -2.0, -10.0],[-2.0, -10.0, 11.0],[-10.0, 11.0, 4.0]],
                  [[1.1, -1.1, -2.1],[-1.1, -2.1, -10.1],[-2.1, -10.1, 21.1],[-10.1, 21.1, 2.1]]])

swapaxed1 = np.swapaxes(array, 1,2)
swapaxed2 = np.swapaxes(array, 2,1)
swapaxed1 == swapaxed2

With what dimensions for array would the results be different?

Thanks for your help to better understand swapaxes in this case. Bests,

Upvotes: 0

Views: 368

Answers (1)

amzon-ex
amzon-ex

Reputation: 1744

In a multidimensional array, a set of indices (non-negative integers) is used to refer to a particular value in that array. The number of dimensions determine the number of such integers required to uniquely specify an element. So, for a m x n x p 3-D array, you need a set of integers (i, j, k). It is important to note that this is an ordered set of integers, meaning the the order in which they are stated is important, because each integer is tied with a dimension of the array.

All swapaxes does is change the order of these indices for a particular value in the array. If you swap axes 0 and 1, the value which was originally referred to by the set of unique integers (i, j, k) will now be referred to by the set by (j, i, k) : the first two indices being swapped, since the axes they are tied to have been swapped.

Hence you see why it always has to be the same: it's a swap, and only the order of reference indices are swapped. (Atleast that's what matters in this case, atop all the stuff that numpy actually performs to achieve this.) In 2-D, a swapaxes operation is just equivalent to a transpose.

Read more about it in this SO discussion. In particular, GoingMyWay's answer might help you visualise it better.

Upvotes: 1

Related Questions