2

When I want to extract specific "rows" (or a higher-dimensional equivalent) from a numpy array, I know that I can use a tuple of indices:

>>> a = np.zeros((3, 4, 5, 6, 7))   # Create a dummy array
>>> a[:, (1, 2), ...].shape   # Get column 1 and 2 and keep the other dimensions as they are
(3, 2, 5, 6, 7)

However, when I use a tuple indexing combined with : or ... and integer indices, the dimensions seem to be reordered:

>>> a[:, (1, 2), :, :, 1].shape   # Expected output: (3, 2, 5, 6)
(2, 3, 5, 6)

I can work around this by separating the indexing into two parts:

>>> a[:, (1, 2)][..., 1].shape   # Gives my desired output
(3, 2, 5, 6)

Why are the dimensions reordered, only when I use both tuple indices and integer indices?

Simon Thor
  • 21
  • 2
  • 1
    The main `indexing` page talks about a mixed basic and advanced index situation. When a slice is between list indices (or scalar), all slice dimensions are moved ot the end. There are SO that talk about this as well. Splitting the dimensions as you do is best option, unless you want to do a transpose. – hpaulj Jan 21 '22 at 21:02
  • Thanks for the comment and for (I assume it was you) linking to a similar question! Was searching around for an answer but I never used the "transpose" keyword. – Simon Thor Jan 21 '22 at 23:04
  • Actually, I found my earlier answer by searching on `[numpy] mixed basic and advanced`. – hpaulj Jan 21 '22 at 23:06

0 Answers0