Samuel
Samuel

Reputation: 6247

logically adding in numpy

I want to do the following operation. But It likes the histogram operation.

maxIndex = 6    
dst  =zeros((1,6))
a    =array([1,2,3,4,7,0,3,4,5,7])
index=array([1,1,1,3,3,4,4,5,5,5])

a's length == index's length,

for i in (a.size):
    dst[index[i]] = dst[index[i]] + a[i]

How can I do this more pythonic. and more efficiently

Upvotes: 2

Views: 72

Answers (1)

Alok Singhal
Alok Singhal

Reputation: 96181

If I understand correctly, I think you are looking for numpy.bincount:

dst = numpy.bincount(index, weights=a, minlength=maxIndex)

This give me array([ 0., 6., 0., 11., 3., 16.]) as the output. If you don't want to calculate maxIndex by hand, you can omit minlength parameter from the function call and numpy will return an appropriately-sized array for you.

Upvotes: 4

Related Questions