Using the advanced indexing in numpy it is possible to
- Return the same location twice, and
- Use the indexed array as a target for assignment.
What I'd like to achieve, is that when I assign values to the same location twice, the values are added instead of the second overwriting the first.
Let me explain this by a code. Let's start with a simple example:
import numpy as np
a = np.array([0, 0])
b = np.array([1, 2])
a[[1, 0]] = b
a
>>> array([2, 1])
This is "regular" fancy indexing: into location 1 of 'a' I copy the location 0 of 'b', into location 0 of 'a' I copy location 1 of 'b'
If I do this:
a = np.array([0, 0])
a[[1, 1]] = b
a
I get this:
>>> array([0, 2])
Into location 1 of 'a' I first copy location 0 of 'b', then I overwrite location 1 of 'a' with location 2 of 'b'. I don't touch location 0 of 'a'.
Instead what I would like to get is this:
>>> array([0, 3])
That is instead of overwriting location 1 of 'a', I would like the value to be added. Is there a numpyic way for this?