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!

2
  • 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! Commented Feb 4, 2016 at 1:32
  • Thank you for the hint, that is exactly what I was looking for. Commented Feb 4, 2016 at 1:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.