I want to sum the values in valsin the elements of a smaller array aspecified in the index list idx.
import numpy as np
a = np.zeros((1,3))
vals = np.array([1,2,3,4])
idx = np.array([0,1,2,2])
a[0,idx] += vals
This leads to the result [[ 1. 2. 4.]], but I want to get the result [[ 1. 2. 7.]], because it should add 3 of valsand 4 of valsto the second element a.
I can achieve what I want:
import numpy as np
a = np.zeros((1,3))
vals = np.array([1,2,3,4])
idx = np.array([0,1,2,2])
for i in np.unique(idx):
fidx = (idx==i).astype(int)
psum = (vals * fidx).sum()
a[0,i] = psum
print(a)
Is there a way to do this with numpy without using a for loop?
source
share