9

I have an array:

a = np.array([0,0,0,0,0,0])

I want to add some other array into each index of a, while the index can appear more than one times. I want to get the some of each index. I write:

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

but get a to be:

array([0, 1, 1, 1, 0, 0])

But what I want is to get:

array([0, 2, 2, 1, 0, 0])

How to implement this in numpy without for loop?

0

4 Answers 4

16

Using pure numpy, AND avoiding a for loop:

np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))

Output:

>>> a = np.array([0,0,0,0,0,0])
>>> np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))
>>> a
array([0, 2, 2, 1, 0, 0])

Please note, this does in-place substitution. This is what is desired by you, but it may not be desired by future viewers. Hence the note :)

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. I even looked at np.add.reduceat but I haven't spent too much time with the ufunc methods so I don't know most of them. The documentation here is even perfect ... "For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once"
Thanks, that's what exactly what I want.
1

You could always just iterate yourself. Something like:

for i in [1,2,2,1,3]:
    a[i] += 1

1 Comment

thanks, but I want to avoid for loop.
1

I don't know of a clever numpy vectorized way to do this... the best I can come up with is:

>>> indices = np.array([1,2,2,1,3])
>>> values = np.array([1,1,1,1,1])
>>> a = np.array([0,0,0,0,0,0])
>>> for i, ix in enumerate(indices):
...   a[ix] += values[i]
... 
>>> a
array([0, 2, 2, 1, 0, 0])

3 Comments

Thanks, but I want to avoid for loop.
@maple -- I understand that, but I don't know of a way to do it. Of course, that isn't to say that there isn't a way to do it (though there might not be). In any event, sometimes having an example of correct (working) code is enough to illuminate the problem for others to take a better crack at it.
@maple Check my answer if you're curious to know of a way to do it. Thanks. Though I completely agree with giving examples to solve problems in different ways.
1

You can do something like (assuming for each index there is a correlated value):

a = np.array([0,0,0,0,0,0])
idxs = np.array([1,2,2,1,3])
vals = np.array([1,1,1,1,1])
for idx, val in zip(idxs,vals):
    a[idx] += val

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.