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.
sum(A[a1:b1]), sum(A[a2:b2]), sum(A[a3:b3]) ...
In terms of run-time, what's the most efficient way of doing this?
Thanks!
Assuming your index pairs are stored in a NumPy array
indices
of shape(n, 2)
andn
is fairly large, it is probably best to avoid any Python loop:Here's another way:
The
cumsum
one above is probably more efficient if there are many indices.If you have a lot of index pairs and your array is long then caching might be an option. I'd try a recursive approach like
Not checked for correctness or efficiency, though. Decreasing the upper index
b
could be used as well.In the first instance I'd try the direct solution:
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.