0

Suppose I have a Numpy array A that has a certain number of dimensions. For the rest of the question I will consider that A is a 4-dimensional array:

>>>A.shape 
(2,2,2,2)

Sometimes, I would like to access the elements

A[:,:,1,:]

, but also sometimes I would like to access the elements

A[:,1,:,:]

, and so on (the position of the '1' in the '1'-colon indexing "chain" is a variable).

How can I do that?

user120404
  • 111
  • 2

1 Answers1

1

When you provide a : when indexing, python calls that a slice. When you provide comma-separated slices, it is really just a tuple of slices.

The : is equivalent to slice(None), so you can get the same effect with the following

>>> my_index = (slice(None), 1, slice(None), slice(None))
>>> A[my_index] == A[:,1,:,:]
True

You can build up your indexing programatically with this knowledge.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86