purefanatic
purefanatic

Reputation: 1023

Modify one element in each row of a numpy array by column indices

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

Upvotes: 1

Views: 994

Answers (1)

Divakar
Divakar

Reputation: 221564

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

array[np.arange(len(indices)), indices] -= 1

Upvotes: 2

Related Questions