Cumulative summation of a numpy array by index

后端 未结 5 586
北海茫月
北海茫月 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:54

    Juh_'s comment is the most efficient solution. Here's working code:

    import numpy as np
    import scipy.ndimage as ni
    
    i = np.array([0,0,1,2,2])
    d = np.array([0,1,2,3,4])
    
    n_indices = i.max() + 1
    print ni.sum(d, i, np.arange(n_indices))
    

提交回复
热议问题