Dschoni
Dschoni

Reputation: 3862

Expected behaviour for repeated numpy operations

I found this answer when looking for a problem on repeated actions on numpy arrays: Increment Numpy multi-d array with repeated indices. My question now is, WHY this behaviour is seen.

import numpy as np
t = np.eye(4)

t[[0,0,1],[0,0,1]]

leads to

array([1.,1.,1.])

so shouldn't

t[[0,0,1],[0,0,1]]+=1 

lead to

[[3,0,0,0],
 [0,2,0,0],
 [0,0,1,0],
 [0,0,0,1]]

?

Upvotes: 2

Views: 50

Answers (1)

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

See the documentation for indexing an array and the difference between basic and advanced indexing.

t[[0,0,1],[0,0,1]] falls under the category of advanced indexing and as stated in the doc:

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

The copy is evaluated before the first increment, so as expected,

import numpy as np
t = np.eye(4)
t[[0,0,1],[0,0,1]] += 1
print(t)

prints:

[[ 2.  0.  0.  0.]
 [ 0.  2.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

As per the comments above, use numpy.ufunc.at or numpy.add.at to get around this.

Upvotes: 1

Related Questions