1
arr = np.arange(12).reshape((3, 2, 2))
indices = np.array([0, 1, 1])

expected_outcome = np.array([[0, 1], [6, 7], [10, 11]])

I'm trying to index this array of shape (3,2,2) with an array of shape (3) containing the y-index of the value I want to get. I tried to make it work with for in statement, but is there an elegant way to do it with numpy?

1
  • I'd probably do np.array([arr[i][indices[i]] for i in range(arr.shape[0])]), but like you said, it would be nice to vectorize that, and it seems like something that would be doable. Commented Jul 25, 2022 at 18:53

1 Answer 1

1

So you want arr[0,0,:], arr[1,1,:], arr[2,1,:]?

How about

In [179]: arr[[0,1,2], [0,1,1]]
Out[179]: 
array([[ 0,  1],
       [ 6,  7],
       [10, 11]])
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know of a way to use the indices variable without a for-loop?
@ichthyophile,do you wmatn arr[np.arange(3), indices]. The key is that the index for a nd arrray should be a tuple of arrays - arrays that broadcast against each other.

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.