EN VI

Numpy Indexing Flips Dimensions?

2024-03-13 18:00:04
How to Numpy Indexing Flips Dimensions

I have a numpy array a of shape (8193, 10, 15, 2, 2). Now, i want to select 2 elements along the 2nd and one along the 5th dimension, starting to count dimensions at 1. However, the slice operations seems to rotate the dimension somehow, and a[:,[0,3],:,:,0].shape results in (2, 8193, 15, 2), i.e. one of the later dimensions ends up being the first (?!). Consecutive indexing a[:,[0,3]][:,:,:,:,0].shape yields (8193, 2, 15, 2), i.e. the expected result. Also a[:,[0,3],0,:,:].shape yields (8193, 2, 2, 2), thus, works as expected. Anyone knows what's going on?

Solution:

According to this NumPy issue, this is expected behaviour.

To quote the response to the filed issue:

This is working as documented. Quoting from https://numpy.org/doc/1.21/reference/arrays.indexing.html#advanced-indexing:

Two cases of index combination need to be distinguished:

  • The advanced indexes are separated by a slice, Ellipsis or newaxis. For example x[arr1, :, arr2].
  • The advanced indexes are all next to each other. For example x[..., arr1, arr2, :] but not x[arr1, :, 1] since 1 is an advanced index in this regard.

In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing).

Your situation appears to be the first. In which case the dimensions resulting from the slice come first, then the other dimensions.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login