Calculate the percentile rank for a given population

I have a “reference population” (say, v=np.random.rand(100)), and I want to calculate the percentile ranking for a given set (for example, np.array([0.3, 0.5, 0.7])).

Easy to calculate one by one:

def percentile_rank(x):
    return (v<x).sum() / len(v)
percentile_rank(0.4)
=> 0.4

(actually there is ootb scipy.stats.percentileofscore- but it does not work on vectors).

np.vectorize(percentile_rank)(np.array([0.3, 0.5, 0.7]))
=> [ 0.33  0.48  0.71]

This gives the expected results, but I feel that there must be a built-in for this.

I can also fool:

pd.concat([pd.Series([0.3, 0.5, 0.7]),pd.Series(v)],ignore_index=True).rank(pct=True).loc[0:2]

0    0.330097
1    0.485437
2    0.718447

This is bad for two reasons:

  • I do not want the test data to [0.3, 0.5, 0.7]be part of the ranking.
  • I do not want to waste time calculating the ranks for a reference population.

So what is the idiomatic way to achieve this?

+4
source share
3 answers

Setup:

In [62]: v=np.random.rand(100)

In [63]: x=np.array([0.3, 0.4, 0.7])

Numpy:

In [64]: (v<x[:,None]).mean(axis=1)
Out[64]: array([ 0.18,  0.28,  0.6 ])

Check:

In [67]: percentile_rank(0.3)
Out[67]: 0.17999999999999999

In [68]: percentile_rank(0.4)
Out[68]: 0.28000000000000003

In [69]: percentile_rank(0.7)
Out[69]: 0.59999999999999998
+3

, pd.cut

s=pd.Series([-np.inf,0.3, 0.5, 0.7])
pd.cut(v,s,right=False).value_counts().cumsum()/len(v)
Out[702]: 
[-inf, 0.3)    0.37
[0.3, 0.5)     0.54
[0.5, 0.7)     0.71
dtype: float64

np.vectorize(percentile_rank)(np.array([0.3, 0.5, 0.7]))
Out[696]: array([0.37, 0.54, 0.71])
+2

quantile:

np.random.seed(123)
v=np.random.rand(100)

s = pd.Series(v)
arr = np.array([0.3,0.5,0.7])

s.quantile(arr)

:

0.3    0.352177
0.5    0.506130
0.7    0.644875
dtype: float64
+2

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


All Articles