有没有一种方便的方法来计算序列或一维numpy数组的百分位数?
我正在寻找类似于Excel的百分位函数的东西。
我查看了NumPy的统计资料,但找不到这个。我能找到的是中位数(50%),但不是更具体的东西。
发布于 2010-05-02 19:46:20
顺便说一句,这里有a pure-Python implementation of percentile function,以防有人不想依赖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/ }}}
发布于 2013-06-12 15:45:25
import numpy as np
a = [154, 400, 1124, 82, 94, 108]
print np.percentile(a,95) # gives the 95th percentile
发布于 2013-03-24 00:35:03
下面是如何在不使用numpy的情况下使用python来计算百分位数。
import math
def percentile(data, perc: int):
size = len(data)
return sorted(data)[int(math.ceil((size * perc) / 100)) - 1]
percentile([10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0], 90)
# 9.0
percentile([142, 232, 290, 120, 274, 123, 146, 113, 272, 119, 124, 277, 207], 50)
# 146
https://stackoverflow.com/questions/2374640
复制相似问题