1

I tried to play around with the indexing of numpy and inplace addition and figured out that it is not doing what I expected

a = np.array([0,0,0])
a[[0,0,1,2]] += [1,2,3,4]
a

which gives me

array([2, 3, 4])

But I would expect element 0 to be 3 (2+1)

Any idea/reference on why this does not work as i expect ?

Or how to make that work ?

Oily
  • 538
  • 3
  • 11
  • Well, to make it work as you expect you could obviously sum up the new additions into a single one, and then do `a[[0,1,2]]+= [3,3,4]`. So I guess the question is more about the "Why does this not work as I expect?" aspect – lucidbrot Oct 11 '22 at 07:30
  • 1
    Perhaps [this answer](https://stackoverflow.com/a/55106031/2550406) helps? I guess if you want to have the same index twice, python will first compute the values to write, and then writes them .... and the value `2` overwrites the value `1` that it very quickly wrote to that same location – lucidbrot Oct 11 '22 at 07:36
  • @lucidbrot, this is a buffering issue, as explained by the docs for `ufunc.at`, https://numpy.org/doc/stable/reference/generated/numpy.ufunc.at.html – hpaulj Oct 11 '22 at 11:05

0 Answers0