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?

2
  • @Kanak Yup. Thanks. Do I delete the question? Commented Oct 10, 2018 at 17:12
  • No do not delete it. You are welcome. Commented Oct 10, 2018 at 17:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.