Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a value, find percentile % with Numpy

Tags:

python

numpy

There are probably better words to describe this question, however what I am trying to do is the opposite of np.percentile(). I have a list of n numbers, and I want to see what percentile of them are smaller than a given value. Right now the way I get this value is by continuously trying different decimals. What I want Numpy to tell me is this:

Given threshold = 0.20 (input), about 99.847781% (output) of the items in list d are below this percentile.

What I do right now to get this number is pretty sketchy:

>>> np.percentile(np.absolute(d), 99.847781)
0.19999962082827874

>>> np.percentile(np.absolute(d), 99.8477816)
0.19999989822334402

>>> np.percentile(np.absolute(d), 99.8477817)
0.19999994445584851

>>> np.percentile(np.absolute(d), 99.8477818)
0.19999999068835939
...
like image 619
cookiedough Avatar asked Jul 30 '18 14:07

cookiedough


People also ask

How do you calculate percentile with Python?

We can use the numpy. percentile() function to calculate percentiles in Python. The numpy. percentile() function is used to calculate the n t h n^{th} nth percentile of the given data (array) along the specified axis.

What is NP percentile in Python?

NumPy percentile is also known as centile is measured and used for the statistics purposes and it indicates the values in the given percentage format of user observations in the group for percentage below and hand waving purpose to say there are 100 equal percentile bands that denotes the user input datas it specified ...


2 Answers

If I'm understanding your question correctly, something like

sum(d < threshold) / len(d)

should do it.

Edit: I missed the absolute value in the question -

sum(np.abs(d) < threshold) / float(len(d))
like image 165
Tim Avatar answered Sep 22 '22 02:09

Tim


Assuming d is a NumPy array, in general, you can do:

(d < threshold).mean()

And for absolute values specifically:

(np.abs(d) < threshold).mean()
like image 40
Martin Marek Avatar answered Sep 18 '22 02:09

Martin Marek