1

(I apologize in advance if this is a duplicate question, though I looked at many similar questions on SO but didn't find a matching solution)

Suppose you have an array

A = np.array([
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
])

and another array

I = np.array([1, 1, 2])

For each row in A, I want to get the i-th element of it, where i is the row-th element of I.

In this case, the output I'd like to have is array([1, 4, 8]).

My most intuitive attempt to do so is:

A[:, I]

then I figured that the desired output is actually the diagonal of it, so A[:, I].diagonal() would do the trick.

But it feels that there's some waste of space and time by doing this way, because it requires an intermediate "big" matrix, which diagonal will be extracted from.

Is there a more efficient to perform this slicing?

0

1 Answer 1

2

This would do the trick:

res = A[np.arange(A.shape[0]), I]
Sign up to request clarification or add additional context in comments.

1 Comment

That's precisely what I was looking for. The speedup and memory saving is huge comparing the .diagonal() method I was doing. Thank you very much.

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.