Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative sum of variable till a given percentile

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?

like image 330
user308827 Avatar asked Dec 11 '22 06:12

user308827


2 Answers

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
like image 117
JoshAdel Avatar answered Dec 13 '22 21:12

JoshAdel


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
like image 21
CT Zhu Avatar answered Dec 13 '22 19:12

CT Zhu