0

I have three arrays

A = array([0, 0, 0, 0])

B = array([0.4, 0.3, 0.2, 0.1])

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

I want to assign to every element i of array A the sum of all elements of array B for which array C points to i. The result should be

A = array([0.7, 0.2, 0.1, 0])

So far I get the desired result as follows:

for i in np.unique(C):
 A[i] = np.sum(B[C==i])

The arrays are large, and the loop is slow. I am trying to accomplish this without a loop, but I don't know how. Thank you for suggestions!

Tobias
  • 514
  • 6
  • 17
  • 1
    As an example of the linked answer, you could do `np.add.at(A,C,B)` to get `array([ 0.7, 0.2, 0.1, 0. ])`-- make sure that A has a float dtype though! – DSM Feb 04 '16 at 01:32
  • Thank you for the hint, that is exactly what I was looking for. – Tobias Feb 04 '16 at 01:46

0 Answers0