Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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

None that I know of, but you can do this

import numpy as np
from itertools import takewhile

a = [15, 40, 124, 282, 914, 308]
p90 = np.percentile(a,90)
print sum(takewhile(lambda x : x < p90,  a))

Out:

461
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top