Increment Numpy array with repeated indices

In numpy >= 1.8, you can also use the at method of the addition ‘universal function’ (‘ufunc’). As the docs note:

For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once.

So taking your example:

a = np.zeros(6).astype('int')
b = [3, 2, 5, 2]

…to then…

np.add.at(a, b, 1)

…will leave a as…

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

Leave a Comment