The cumulative sum of the variable to the specified percentile

I would like to sum all the values ​​in the array to the given percentile. For instance.

import numpy as np
a = [15, 40, 124, 282, 914, 308]
print np.percentile(a,90)

The 90th percentile is ~ 611, and the total before that is 461

Is there any function in Python that can do this?

+4
source share
3 answers
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

It:

%timeit A[:(A<np.percentile(a, 90)).argmin()].sum()
10000 loops, best of 3: 191 Β΅s per loop
+3
source

No I know, but you can do it

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))

Of:

461
+4
source
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
+3
source

Source: https://habr.com/ru/post/1534342/


All Articles