Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

python - Numpy sum of values in subarrays between pairs of indices

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...