Cumulative summation of a numpy array by index

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

    If I understand the question correctly, there is a fast function for this (as long as the data array is 1d)

    >>> i = np.array([0,0,1,2,2])
    >>> d = np.array([0,1,2,3,4])
    >>> np.bincount(i, weights=d)
    array([ 1.,  2.,  7.])
    

    np.bincount returns an array for all integers range(max(i)), even if some counts are zero

提交回复
热议问题