计算相对于给定人口的百分位数等级

时间:2018-01-24 21:46:12

标签: python pandas numpy rank percentile

我有"参考人口" (例如,v=np.random.rand(100))我想计算给定集合的百分位数等级(比如np.array([0.3, 0.5, 0.7]))。

逐个计算很容易:

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

(实际上,有一个ootb scipy.stats.percentileofscore - 但对矢量有效。)

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

这会产生预期的结果,但我觉得应该有一个内置的。

我也可以作弊:

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

这有两个方面很糟糕:

  1. 我不希望测试数据[0.3, 0.5, 0.7]成为排名的一部分。
  2. 我不想浪费时间为参考人群计算排名。
  3. 那么,实现这个的惯用方式是什么?

3 个答案:

答案 0 :(得分:3)

设定:

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

检查:

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

答案 1 :(得分:2)

我认为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 :(得分: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
相关问题