如何获得pandas数据框中行的百分位数?

时间:2018-06-11 18:39:54

标签: python pandas numpy scipy percentile

Example DataFrame Values -  

0     78
1     38
2     42
3     48
4     31
5     89
6     94
7    102
8    122
9    122  

stats.percentileofscore(temp['INCOME'].values, 38, kind='mean')
15.0

stats.percentileofscore(temp['INCOME'].values, 38, kind='strict')
10.0

stats.percentileofscore(temp['INCOME'].values, 38, kind='weak')
20.0

stats.percentileofscore(temp['INCOME'].values, 38, kind='rank')
20.0

temp['INCOME'].rank(pct=True)
1    0.20 (Only showing the 38 value index)

temp['INCOME'].quantile(0.11)
37.93

temp['INCOME'].quantile(0.12)
38.31999999999999

Based on the results above, you can see none of the methods are consistent
with the pd.quantiles() method.

我需要为数据框中的每一行(255M行)获取一列的百分位数,但无法找到返回pd.quantile方法的任何函数/方法}& np.percentile

我尝试过以下方法/功能 -

.rank(pct=True)

此方法仅返回按顺序排列的值,而不是使用我正在寻找的百分位数方法。与pd.quantiles

不一致
scipy.stats.percentileofscore  

这种方法几乎与我正在寻找的方法更接近但仍未与“线性插值”完全一致。出于某种原因的方法。 'linear interpolation'

我查看了与此问题相关的每个SO答案,但没有一个使用我需要使用的相同插值方法,因此请不要将其标记为重复,除非您可以验证它们是否正确。重新使用相同的方法。

此时我的最后一个选择是找到所有100百分位数的bin截止值并以这种方式应用它或自己计算线性插值但这似乎非常低效并且将永远适用于255M记录。

还有其他建议吗?

谢谢!

3 个答案:

答案 0 :(得分:8)

TL; DR

使用

sz = temp['INCOME'].size-1
temp['PCNT_LIN'] = temp['INCOME'].rank(method='max').apply(lambda x: 100.0*(x-1)/sz)

   INCOME    PCNT_LIN
0      78   44.444444
1      38   11.111111
2      42   22.222222
3      48   33.333333
4      31    0.000000
5      89   55.555556
6      94   66.666667
7     102   77.777778
8     122  100.000000
9     122  100.000000

答案

一旦你理解了这些机制,它实际上非常简单。当您在寻找分数的百分位数时,您已经在每一行中获得了分数。剩下的唯一步骤就是要了解您需要小于或等于的数字的百分位数。这正是scipy.stats.percentileofscore()的参数 kind ='weak'DataFrame.rank() method ='average'的参数。要将其反转,请使用 interpolation ='lower'运行Series.quantile()

因此,scipy.stats.percentileofscore()Series.rank()Series.quantile() 的行为一致,见下文:

In[]:
temp = pd.DataFrame([  78, 38, 42, 48, 31, 89, 94, 102, 122, 122], columns=['INCOME'])
temp['PCNT_RANK']=temp['INCOME'].rank(method='max', pct=True)
temp['POF']  = temp['INCOME'].apply(lambda x: scipy.stats.percentileofscore(temp['INCOME'], x, kind='weak'))
temp['QUANTILE_VALUE'] = temp['PCNT_RANK'].apply(lambda x: temp['INCOME'].quantile(x, 'lower'))
temp['RANK']=temp['INCOME'].rank(method='max')
sz = temp['RANK'].size - 1 
temp['PCNT_LIN'] = temp['RANK'].apply(lambda x: (x-1)/sz)
temp['CHK'] = temp['PCNT_LIN'].apply(lambda x: temp['INCOME'].quantile(x))

temp

Out[]:
   INCOME  PCNT_RANK    POF  QUANTILE_VALUE  RANK  PCNT_LIN    CHK
0      78        0.5   50.0              78   5.0  0.444444   78.0
1      38        0.2   20.0              38   2.0  0.111111   38.0
2      42        0.3   30.0              42   3.0  0.222222   42.0
3      48        0.4   40.0              48   4.0  0.333333   48.0
4      31        0.1   10.0              31   1.0  0.000000   31.0
5      89        0.6   60.0              89   6.0  0.555556   89.0
6      94        0.7   70.0              94   7.0  0.666667   94.0
7     102        0.8   80.0             102   8.0  0.777778  102.0
8     122        1.0  100.0             122  10.0  1.000000  122.0
9     122        1.0  100.0             122  10.0  1.000000  122.0

现在,在列PCNT_RANK中,您获得的值的比率小于或等于列INCOME中的值。但是,如果您想要“插值”比率,则它位于PCNT_LIN列中。当您使用Series.rank()进行计算时,它非常快,并且会在几秒钟内处理您的255M数字。

在这里,我将解释如何通过quantile()插值使用linear获得价值:

temp['INCOME'].quantile(0.11)
37.93

我们的数据temp['INCOME']只有十个值。根据你link to Wiki的公式,第11百分位的等级是

rank = 11*(10-1)/100 + 1 = 1.99

rank 的截断部分为1,对应于值31,等级2(即下一个bin)的值为38. fraction的值为 rank 的小数部分。这导致了结果:

 31 + (38-31)*(0.99) = 37.93

对于值本身,fraction部分必须为零,因此很容易进行逆计算以获得百分位数:

p = (rank - 1)*100/(10 - 1)

我希望我说得更清楚。

答案 1 :(得分:1)

这似乎有效:

A = np.sort(temp['INCOME'].values)
np.interp(sample, A, np.linspace(0, 1, len(A)))

例如:

>>> temp.INCOME.quantile(np.interp([37.5, 38, 122, 121], A, np.linspace(0, 1, len(A))))
0.103175     37.5
0.111111     38.0
1.000000    122.0
0.883333    121.0
Name: INCOME, dtype: float64

请注意,只有在想要查询足够多的值时,此策略才有意义。否则分拣太贵了。

答案 2 :(得分:0)

让我们考虑以下数据框:

DataFrame

为了获得pandas Dataframe中列的百分位数,我们使用以下代码:

 survey['Nationality'].value_counts(normalize='index')

输出:

美国0.333333

中国0.250000

印度0.250000

孟加拉国0.166667

名称:国籍,dtype:float64

为了获得pandas Dataframe中列相对于另一个分类列的百分位数

pd.crosstab(survey.Sex,survey.Handedness,normalize = 'index')

输出如下所示

Output