Summing array values ​​by repeating the index for the array

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?

+4
source share
1 answer

Perhaps with np.add.at, until the alignment of the figures, i.e. ashould be here 1D.

a = a.squeeze()
np.add.at(a, idx, vals)

a
array([1., 2., 7.])
+4
source

Source: https://habr.com/ru/post/1693690/


All Articles