I would like to sum up all the values in an array till a given percentile. E.g.
import numpy as np
a = [15, 40, 124, 282, 914, 308]
print np.percentile(a,90)
The 90th percentile is ~611 and the cumulative sum till then is 461
Is there any function in Python which can do that?
import numpy as np
a = np.array([15, 40, 124, 282, 914, 308])
b = np.cumsum(a)
p90 = np.percentile(a, 90)
print b[b < p90][-1] #461
A=np.array(a)
A[:(A<np.percentile(a, 90)).argmin()].sum() #461
@JoshAdel's
%%timeit
...: b = np.cumsum(a)
...: p90 = np.percentile(a, 90)
...: b[b < p90][-1]
...:
1000 loops, best of 3: 217 µs per loop
This:
%timeit A[:(A<np.percentile(a, 90)).argmin()].sum()
10000 loops, best of 3: 191 µs per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With