Cumulative summation of a numpy array by index

后端 未结 5 591
北海茫月
北海茫月 2021-02-08 11:54

Assume you have an array of values that will need to be summed together

d = [1,1,1,1,1]

and a second array specifying which elements need to be

5条回答
  •  生来不讨喜
    2021-02-08 12:50

    This solution should be more efficient for large arrays (it iterates over the possible index values instead of the individual entries of i):

    import numpy as np
    
    i = np.array([0,0,1,2,2])
    d = np.array([0,1,2,3,4])
    
    i_max = i.max()
    c = np.empty(i_max+1)
    for j in range(i_max+1):
        c[j] = d[i==j].sum()
    
    print c
    [1. 2. 7.]
    

提交回复
热议问题