如何用python / numpy计算百分位数?

有一个方便的方法来计算序列或一维numpy数组的百分位数吗?

我正在寻找类似于Excel百分比函数的东西。

我查看了NumPy的统计参考,并找不到这个。 我能find的只是中位数(第50百分位数),而不是更具体的。

您可能对SciPy Stats软件包感兴趣。 它具有百分之百的function ,以及许多其他的统计好东西。

percentile() 也可用于numpy

 import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) # return 50th percentile, eg median. print p 3.0 

这张票让我相信他们不会将percentile()变成numpy。

顺便说一句,有一个纯Python的百分位函数的实现 ,如果一个人不想依靠scipy。 该function复制如下:

 ## {{{ 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)]) * (ck) d1 = key(N[int(c)]) * (kf) return d0+d1 # median is 50th percentile. median = functools.partial(percentile, percent=0.5) ## end of http://code.activestate.com/recipes/511478/ }}} 
 import numpy as np a = [154, 400, 1124, 82, 94, 108] print np.percentile(a,95) # gives the 95th percentile 

我通常认为,百分位数的定义是所期望的结果是来自所提供的列表中的值,其中P百分比值被find…这意味着结果必须来自集合,而不是集合元素之间的内插。 为了得到这个,你可以使用一个更简单的函数。

 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] 

检查scipy.stats模块:

  scipy.stats.scoreatpercentile 

这里是如何做到这一点,没有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) 

要计算一系列的百分位数,请运行:

 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} 
Interesting Posts