Is it possible to combine (add) values of a vector according to integer value of another vector

  • A+

I'm trying to add float values of a vector according to integer values from another vector.

for instance if I have:

import numpy as np a = np.array([0.1,0.2,0.3,0.4,0.5,0.6,07.3,0.8,0.9,1.,1.2,1.4]) b = np.array([0,0,0,0,0,1,1,1,2,2,2,2]).astype(int) 

I would like to add the 5 first value of the a vector together (because the 5 first values of b are 0), the 3 next values together (because the 3 next values of b are 1) and so on. So At the end I woudl expect to have

c = function(a,b) c = [0.1+0.2+0.3+0.4+0.5,  0.6+7.3+0.8, 0.9+1.+1.2+1.4] 


Approach #1 : We can make use of np.bincount with b as the bins and a as weights array -

In [203]: np.bincount(b,a) Out[203]: array([1.5, 8.7, 4.5]) 

Approach #2 : Another leveraging matrix-multiplication -

In [210]: (b == np.arange(b.max()+1)[:,None]).dot(a) Out[210]: array([1.5, 8.7, 4.5]) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: