5

Suppose you have the following code

a = np.ones(8)
pos = np.array([1, 3, 5, 3])

a[pos] # returns array([ 1.,  1.,  1.,  1.]), where the 2nd and 4th el are the same
a[pos] +=1 

The last instruction returns

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

But I'd like that assignments over same indices to be summed up, so as to obtain

array([ 1.,  2.,  1.,  3.,  1.,  2.,  1.,  1.])

Someone has already experienced this same situation?

Seanny123
  • 8,776
  • 13
  • 68
  • 124
diningphil
  • 416
  • 5
  • 18

1 Answers1

9

Using np.add.at

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.

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

print(a)
array([ 1.,  2.,  1.,  3.,  1.,  2.,  1.,  1.])

Do note that the function works in-place.

cs95
  • 379,657
  • 97
  • 704
  • 746