Answers:
您可能对SciPy Stats软件包感兴趣。它具有您需要的百分位数功能和许多其他统计功能。
percentile()
可在numpy
太。
import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print p
3.0
这张票使我相信他们不会percentile()
很快集成到numpy中。
df.groupby('key')[['value']].agg(lambda g: np.percentile(g, 10))
顺便说一句,有一个纯Python实现的百分位数功能,以防万一不想依赖scipy。该函数复制如下:
## {{{ http://code.activestate.com/recipes/511478/ (r1)
import math
import functools
def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.
@return - the percentile of the values
"""
if not N:
return None
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(N[int(k)])
d0 = key(N[int(f)]) * (c-k)
d1 = key(N[int(c)]) * (k-f)
return d0+d1
# median is 50th percentile.
median = functools.partial(percentile, percent=0.5)
## end of http://code.activestate.com/recipes/511478/ }}}
percentile
知道用什么N
呢?在函数调用中未指定。
N
在计算百分位数之前先转换数据。假设您实际上有一个元组列表,N = [(1, 2), (3, 1), ..., (5, 1)]
并且想要获得元组第一个元素的百分位数,然后选择key=lambda x: x[0]
。您还可以在计算百分位数之前对列表元素应用一些(顺序更改)转换。
这是不使用numpy的方法,仅使用python计算百分位数。
import math
def percentile(data, percentile):
size = len(data)
return sorted(data)[int(math.ceil((size * percentile) / 100)) - 1]
p5 = percentile(mylist, 5)
p25 = percentile(mylist, 25)
p50 = percentile(mylist, 50)
p75 = percentile(mylist, 75)
p95 = percentile(mylist, 95)
我通常看到的百分位数定义期望结果是所提供的列表中的值,在该列表下找到P值的百分比...这意味着结果必须来自集合,而不是集合元素之间的插值。为此,您可以使用更简单的功能。
def percentile(N, P):
"""
Find the percentile of a list of values
@parameter N - A list of values. N must be sorted.
@parameter P - A float value from 0.0 to 1.0
@return - The percentile of the values.
"""
n = int(round(P * len(N) + 0.5))
return N[n-1]
# A = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# B = (15, 20, 35, 40, 50)
#
# print percentile(A, P=0.3)
# 4
# print percentile(A, P=0.8)
# 9
# print percentile(B, P=0.3)
# 20
# print percentile(B, P=0.8)
# 50
如果您希望从提供的列表中获取等于或低于P值百分比的值,请使用以下简单修改:
def percentile(N, P):
n = int(round(P * len(N) + 0.5))
if n > 1:
return N[n-2]
else:
return N[0]
或使用@ijustlovemath建议的简化形式:
def percentile(N, P):
n = max(int(round(P * len(N) + 0.5)), 2)
return N[n-2]
PERCENTILE
函数将返回以下百分你的上的例子:3.7 = percentile(A, P=0.3)
,0.82 = percentile(A, P=0.8)
,20 = percentile(B, P=0.3)
,42 = percentile(B, P=0.8)
。
n = int(...)
一个max(int(...), 1)
函数
从开始Python 3.8
,标准库附带的quantiles
功能作为statistics
模块的一部分:
from statistics import quantiles
quantiles([1, 2, 3, 4, 5], n=100)
# [0.06, 0.12, 0.18, 0.24, 0.3, 0.36, 0.42, 0.48, 0.54, 0.6, 0.66, 0.72, 0.78, 0.84, 0.9, 0.96, 1.02, 1.08, 1.14, 1.2, 1.26, 1.32, 1.38, 1.44, 1.5, 1.56, 1.62, 1.68, 1.74, 1.8, 1.86, 1.92, 1.98, 2.04, 2.1, 2.16, 2.22, 2.28, 2.34, 2.4, 2.46, 2.52, 2.58, 2.64, 2.7, 2.76, 2.82, 2.88, 2.94, 3.0, 3.06, 3.12, 3.18, 3.24, 3.3, 3.36, 3.42, 3.48, 3.54, 3.6, 3.66, 3.72, 3.78, 3.84, 3.9, 3.96, 4.02, 4.08, 4.14, 4.2, 4.26, 4.32, 4.38, 4.44, 4.5, 4.56, 4.62, 4.68, 4.74, 4.8, 4.86, 4.92, 4.98, 5.04, 5.1, 5.16, 5.22, 5.28, 5.34, 5.4, 5.46, 5.52, 5.58, 5.64, 5.7, 5.76, 5.82, 5.88, 5.94]
quantiles([1, 2, 3, 4, 5], n=100)[49] # 50th percentile (e.g median)
# 3.0
quantiles
对于给定的分布,返回切分点dist
列表,这些n - 1
切点将分n
位数间隔(以等概率dist
分为n
连续间隔)划分为:
statistics.quantiles(dist,*,n = 4,method ='exclusive')
在那里n
,在我们的案例(percentiles
)是100
。
要计算系列的百分位数,请运行:
from scipy.stats import rankdata
import numpy as np
def calc_percentile(a, method='min'):
if isinstance(a, list):
a = np.asarray(a)
return rankdata(a, method=method) / float(len(a))
例如:
a = range(20)
print {val: round(percentile, 3) for val, percentile in zip(a, calc_percentile(a))}
>>> {0: 0.05, 1: 0.1, 2: 0.15, 3: 0.2, 4: 0.25, 5: 0.3, 6: 0.35, 7: 0.4, 8: 0.45, 9: 0.5, 10: 0.55, 11: 0.6, 12: 0.65, 13: 0.7, 14: 0.75, 15: 0.8, 16: 0.85, 17: 0.9, 18: 0.95, 19: 1.0}
如果您需要答案成为输入numpy数组的成员,请执行以下操作:
只是要补充一点,默认情况下numpy中的percentile函数将输出计算为输入向量中两个相邻条目的线性加权平均值。在某些情况下,人们可能希望返回的百分位数是向量的实际元素,在这种情况下,从v1.9.0开始,您可以使用“插值”选项,并使用“较低”,“较高”或“最近”。
import numpy as np
x=np.random.uniform(10,size=(1000))-5.0
np.percentile(x,70) # 70th percentile
2.075966046220879
np.percentile(x,70,interpolation="nearest")
2.0729677997904314
后者是向量中的实际项,而前者是两个向量项的线性插值,它们与百分位数接壤
计算一维numpy序列或矩阵的百分位数的便捷方法是使用numpy.percentile < https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html >。例:
import numpy as np
a = np.array([0,1,2,3,4,5,6,7,8,9,10])
p50 = np.percentile(a, 50) # return 50th percentile, e.g median.
p90 = np.percentile(a, 90) # return 90th percentile.
print('median = ',p50,' and p90 = ',p90) # median = 5.0 and p90 = 9.0
但是,如果您的数据中有任何NaN值,则上述功能将无用。在这种情况下,建议使用的函数是numpy.nanpercentile < https://docs.scipy.org/doc/numpy/reference/generation/numpy.nanpercentile.html >函数:
import numpy as np
a_NaN = np.array([0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.])
a_NaN[0] = np.nan
print('a_NaN',a_NaN)
p50 = np.nanpercentile(a_NaN, 50) # return 50th percentile, e.g median.
p90 = np.nanpercentile(a_NaN, 90) # return 90th percentile.
print('median = ',p50,' and p90 = ',p90) # median = 5.5 and p90 = 9.1
在上面显示的两个选项中,您仍然可以选择插值模式。请按照以下示例进行操作,以便于理解。
import numpy as np
b = np.array([1,2,3,4,5,6,7,8,9,10])
print('percentiles using default interpolation')
p10 = np.percentile(b, 10) # return 10th percentile.
p50 = np.percentile(b, 50) # return 50th percentile, e.g median.
p90 = np.percentile(b, 90) # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1.9 , median = 5.5 and p90 = 9.1
print('percentiles using interpolation = ', "linear")
p10 = np.percentile(b, 10,interpolation='linear') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='linear') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='linear') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1.9 , median = 5.5 and p90 = 9.1
print('percentiles using interpolation = ', "lower")
p10 = np.percentile(b, 10,interpolation='lower') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='lower') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='lower') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1 , median = 5 and p90 = 9
print('percentiles using interpolation = ', "higher")
p10 = np.percentile(b, 10,interpolation='higher') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='higher') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='higher') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 2 , median = 6 and p90 = 10
print('percentiles using interpolation = ', "midpoint")
p10 = np.percentile(b, 10,interpolation='midpoint') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='midpoint') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='midpoint') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 1.5 , median = 5.5 and p90 = 9.5
print('percentiles using interpolation = ', "nearest")
p10 = np.percentile(b, 10,interpolation='nearest') # return 10th percentile.
p50 = np.percentile(b, 50,interpolation='nearest') # return 50th percentile, e.g median.
p90 = np.percentile(b, 90,interpolation='nearest') # return 90th percentile.
print('p10 = ',p10,', median = ',p50,' and p90 = ',p90)
#p10 = 2 , median = 5 and p90 = 9
如果您的输入数组仅包含整数值,那么您可能会对百分位数答案作为整数感兴趣。如果是这样,请选择插值模式,例如“较低”,“较高”或“最近”。