## {{{ 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/ }}}
您可能对SciPy Stats包感兴趣。它有the percentile function你在追求和许多其他的统计好处。
在
numpy
中也有percentile()
is available。This ticket让我相信他们不会很快将percentile()
集成到numpy中。顺便说一下,这里有a pure-Python implementation of percentile function,以防有人不想依赖scipy。函数复制如下:
相关问题 更多 >
编程相关推荐