How to accumulate an array by index in numpy?

I have an array:

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

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

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

but get a:

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

But I want to get:

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

How to implement this in numpy without a loop?

+5
source share
4 answers

Using pure numpy , and avoiding the 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 that this is a replacement in place. This is what you want, but it may not be desirable for future viewers. Hence the note :)

+9
source

You can always just iterate over yourself. Sort of:

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

I don't know how to do this with a smart amount of numpy. 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]) 
+1
source

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

 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 
+1
source

All Articles