Sum array by number in numpy

前端 未结 8 1151
别跟我提以往
别跟我提以往 2020-11-30 08:51

Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want to sum the items in the first array by group (the second array) and obtain n-groups

8条回答
  •  野性不改
    2020-11-30 09:24

    You're all wrong! The best way to do it is:

    a = [1,2,3,4,5,6]
    ix = [0,0,1,2,2,1]
    accum = np.zeros(np.max(ix)+1)
    np.add.at(accum, ix, a)
    print accum
    > array([ 3.,  9.,  9.])
    

提交回复
热议问题