Numpy sum of values in subarrays between pairs of indices

后端 未结 4 1941
情书的邮戳
情书的邮戳 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条回答
  •  萌比男神i
    2020-12-21 04:51

    In the first instance I'd try the direct solution:

    [np.sum(A[a:b]) for (a,b) in ab]
    

    where ab is the sequence of pairs.

    A[a:b] creates a view on the array; there's no copying of the data involved.

    If this turns out to be too slow, please tell us more about the size of A, how many pairs of indices you expect to get, whether the (a,b) ranges tend to overlap, etc.

提交回复
热议问题