Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a NumPy function to compute partial sums?

Given a 1-D array, A and a list of n unique and sorted indices idx, I would like to calculate sums of A[idx[i]:idx[i + 1]] for i = 0 to n - 1. A for-based solution is:

S = [A[idx[i]:idx[i + 1]].sum() for i in range(n - 1)]

But I suppose this would be very slow if n is large as it is done at Python level. Is there a NumPy function to achieve this (hopefully faster)?

like image 308
MikeL Avatar asked Feb 04 '26 07:02

MikeL


1 Answers

You are looking for the reduceat method of np.add:

np.add.reduceat(A, idx)[:-1]

The [:-1] is just there to remove the last element that reduceat appends with the sum from idx[-1] to A.size.

like image 181
Mad Physicist Avatar answered Feb 06 '26 19:02

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!