Attention lab question

Can any one please explain the use of np.swapaxes(key, -1, -2) for transposing? swap the second last axis with last axis? Why not use normal transposing? I don’t quite understand ~
Thank you!

Hi @hknguyen20

In simple words:

  • np.transpose reverses the order of shape (for example, array of shape (3, 4, 5, 6) after transpose becomes (6, 5, 4, 3))
  • while np.swapaxes allows you to indicate the two axes you want to swap (for example, (3, 4, 5, 6) can become (3, 4, 6, 5)

An example with 3D array (3, 4, 5):


Thanks for providing me a better understanding of the two methods! Upon further exploration, the key is 3D with an additional dimension shape 1 at axis 0. We would want to transpose the last two axes only so that’s why we use swapaxes. If my understanding is correct, the two methods are interchangeable for 2D arrays.