Numpy sum of values in subarrays between pairs of indices

后端 未结 4 1952
情书的邮戳
情书的邮戳 2020-12-21 03:58

Suppose I have an array A. I have a series of index pairs (a1, b1), (a2, b2) ... (an, bn)

I want to obtain all the sums of the elements between those pairs. i.e.

4条回答
  •  长情又很酷
    2020-12-21 04:37

    Assuming your index pairs are stored in a NumPy array indices of shape (n, 2) and n is fairly large, it is probably best to avoid any Python loop:

    c = numpy.r_[0, A.cumsum()][indices]
    sums = c[:,1] - c[:,0]
    

提交回复
热议问题