Numpy sum of values in subarrays between pairs of indices

后端 未结 4 1942
情书的邮戳
情书的邮戳 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:42

    Here's another way:

    a = np.random.rand(3000)
    indices = np.array([[0,3], [9,20], [5,30], [9,33]])
    sums = np.add.reduceat(a, indices.ravel())[::2]
    
    assert np.all(sums == np.array([a[i:j].sum() for i,j in indices]))
    

    The cumsum one above is probably more efficient if there are many indices.

提交回复
热议问题