How to accumulate an array by index in numpy? [duplicate] How to accumulate an array by index in numpy? [duplicate] arrays arrays

How to accumulate an array by index in numpy? [duplicate]


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]))>>> aarray([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 :)


You could always just iterate yourself. Something like:

for i in [1,2,2,1,3]:    a[i] += 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]... >>> aarray([0, 2, 2, 1, 0, 0])