计算列中值的百分位数

Blu*_*ire 4 python statistics distribution pandas

我有一个带有数字值的列的数据框。该列不是正态分布所近似的。给定另一个数值(不在此列中),如何计算其在该列中的百分位数?也就是说,如果该值大于该列中值的80%但小于其他20%,则该值将位于第20个百分点。

小智 9

要找到相对于数组(或您的情况下为dataframe列)的值的百分位数,请使用scipy函数stats.percentileofscore()

例如,如果我们有一个值x(数据框中没有的其他数值)和一个引用数组arr(数据框中的列),则可以找到xby 的百分位数:

from scipy import stats
percentile = stats.percentileofscore(arr, x)
Run Code Online (Sandbox Code Playgroud)

注意,stats.percentileofscore()函数的第三个参数对百分位数的结果值具有重要影响。kind。您可以选择rankweakstrict,和mean。有关更多信息,请参阅文档

有关差异的示例:

>>> df
   a
0  1
1  2
2  3
3  4
4  5

>>> stats.percentileofscore(df['a'], 4, kind='rank')
80.0

>>> stats.percentileofscore(df['a'], 4, kind='weak')
80.0

>>> stats.percentileofscore(df['a'], 4, kind='strict')
60.0

>>> stats.percentileofscore(df['a'], 4, kind='mean')
70.0
Run Code Online (Sandbox Code Playgroud)

最后要注意的是,如果您的值大于该列中其他值的80%,则该值应在第80个百分点(请参见上面的示例以了解该kind方法对最终得分的影响程度),而不是第20个百分点。有关更多信息,请参见此Wikipedia文章


Ami*_*pta 5

可能很晚了但仍然

df['column_name'].describe()
Run Code Online (Sandbox Code Playgroud)

将为您提供常规的 25、50 和 75 百分位数以及一些附加数据,但如果您想要某些特定值的百分位数,那么

df['column_name'].describe(percentiles=[0.1, 0.2, 0.3, 0.5])
Run Code Online (Sandbox Code Playgroud)

这将为您提供第 10 个、第 20 个、第 30 个和第 50 个百分位数。您可以根据需要提供任意多个值。

可以像字典一样访问生成的对象:

desc = df['column_name'].describe(percentiles=[0.1, 0.2, 0.3, 0.5])
print(desc)
print(desc['10%'])
Run Code Online (Sandbox Code Playgroud)


Bin*_*ven 1

对列进行排序,并查看该值是否位于前 20% 或任何百分位数内。

例如:

def in_percentile(my_series, val, perc=0.2): 
    myList=sorted(my_series.values.tolist())
    l=len(myList)
    return val>myList[int(l*perc)]
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要实际的百分位数,只需使用searchsorted

my_series.values.searchsorted(val)/len(my_series)*100
Run Code Online (Sandbox Code Playgroud)