numpy.array.__iadd__ and repeated indices [duplicate]
Solution 1:
for this numpy 1.8 added the at
reduction:
at(a, indices, b=None)
Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. For addition ufunc, this method is equivalent to
a[indices] += b
, except that results are accumulated for elements that are indexed more than once. For example,a[[0,0]] += 1
will only increment the first element once because of buffering, whereasadd.at(a, [0,0], 1)
will increment the first element twice... versionadded:: 1.8.0
In [1]: A = np.array([0, 0, 0])
In [2]: B = np.array([1, 1, 1, 1, 1, 1])
In [3]: idx = [0, 0, 1, 1, 2, 2]
In [4]: np.add.at(A, idx, B)
In [5]: A
Out[5]: array([2, 2, 2])
Solution 2:
How about:
A = np.array([1, 2, 3])
idx = [0, 0, 1, 1, 2, 2]
A += np.bincount(idx, minlength=len(A))
Obviously it's even more simple if A starts off as zeros:
A = np.bincount(idx)