我有“引用人口”(例如,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
这在两个方面是不好的:
- 我不希望测试数据
[0.3, 0.5, 0.7]
成为排名的一部分。 - 我不想浪费时间计算引用人群的排名。
那么,实现这一目标的惯用方法是什么?
最佳答案
设置:
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
关于python - 计算相对于给定人口的百分位数排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48432153/