2

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

3
  • possible duplicate of Assigning identical array indices at once in Python/Numpy Commented Aug 30, 2013 at 12:54
  • The 1D case was just asked here. Commented Aug 30, 2013 at 12:55
  • This question appears to belong on codereview.stackexchange.org Commented Mar 2, 2014 at 0:10

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

minlength should be set to maxIndex to match OP's output.
@KennyTM I think you're right. I wasn't sure what maxIndex was doing in his question. What the OP probably really wants is the default behavior, without the minlength parameter since that will return an array with a non-zero last element...
very nice. That's what i want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.