1

I have a numpy array such as arr = np.arange(16).reshape(2,2,2,2)

I want to dynamically access arr[:, dim2, dim3], when I have (dim2, dim3) as a tuple. What is the best way to do this?

2
  • Are you thinking of a case where you know the dimensions of your array in advance, or are you trying to think of a method that would work even if you didn't know, say, the number of dimensions in the array? Commented Feb 27, 2020 at 13:35
  • @jjramsey The latter, I'll make that clearer. Commented Feb 27, 2020 at 13:37

2 Answers 2

3

Try something like this if the number of dimensions might not be the same for your array:

some_tuple = (dim2, dim3) # Could be (dim2, dim3, ..., dimN)

arr[(slice(None),) + some_tuple]

In this particular case, (slice(None),) + some_tuple is the same as (slice(None), dim2, dim3). slice(None) is more or less equivalent to ":", but it can be used in more places than ":". Notice that I put slice(None) in a single-element tuple (i.e. (slice(None),)) so that I can add it to some_tuple. Notice as well that there's a comma after slice(None), i.e., I don't just write (slice(None)) without a comma. It won't work without the extra comma.

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

1 Comment

Nice answer. Alternatively arr[(slice(None), *some_tuple)] could also be an option, this way you avoid creating a tuple
0
some_tuple = (dim2, dim3)

arr[:, some_tuple[0], some_tuple[1]]

1 Comment

Thanks! Is there a general way to do this, especially if I have a long tuple?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.