1

I would like to decrement exactly one element in each row of a two-dimensional array, given some indices, one for each row. So basically I want the following to be vectorized:

for row, col in enumerate(indices):
    array[row,col] -= 1

I can select the elements which I want to modify using numpy.choose, but then unfortunately those elements just get copied. Or in other words, something like this does not work:

selection = np.choose(indices, array.T)
selection -= 1

1 Answer 1

2

Use integer array indexing for a vectorized access and thus assignment -

array[np.arange(len(indices)), indices] -= 1
Sign up to request clarification or add additional context in comments.

2 Comments

Cool. I guess we can't get rid of the range?
Nope, we can't get rid of it. Creating such a range array isn't expensive really.

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.