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

308 投票
12 回答
478074 浏览
提问于 2025-04-15 19:58

有没有简单的方法可以计算一个序列或一维的 numpy 数组的百分位数?

我想要的功能和Excel里的百分位数函数差不多。

12 个回答

40

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

88

顺便提一下,这里有一个纯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/ }}}
391

NumPy有一个函数叫做 np.percentile()

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

SciPy除了有很多其他统计工具外,还有一个函数叫做 scipy.stats.scoreatpercentile()

撰写回答