python:numpy使用线性插值计算百分位

2024-09-24 10:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算百分位数后,阅读了维基百科我实现了简单的公式

def _percentile(numList, percentile):
    numList.sort()
    n = int(round(percentile * len(numList) + 0.5))
    if n > 1:
        return numList[n-2]
    else:
        return 0

但是我想做的是wiki中提到的插值版本:(http://en.wikipedia.org/wiki/Percentile#Linear_interpolation_between_closest_ranks)我在google中搜索并找到了numpy,但是我认为即使是对于简单的公式,我也没有得到正确的值。当我试着传递这个值来做插值时,它给了我一个错误。(http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html

让我们从以下列表开始:

^{pr2}$

根据我的方法:我得到原始列表的实际值,该值表示我要查找的百分位数:

>>> print percentile(B, P=0.)
0
>>> print percentile(B, P=0.1)
0
>>> print percentile(B, P=0.2)
15
>>> print percentile(B, P=0.3)
15
>>> print percentile(B, P=0.4)
20
>>> print percentile(B, P=0.5)
20
>>> print percentile(B, P=0.6)
35
>>> print percentile(B, P=0.7)
35
>>> print percentile(B, P=0.8)
40
>>> print percentile(B, P=0.9)
40
>>> print percentile(B, P=0.95)
40
>>> print percentile(B, P=1.0)
50

但是如果我使用numpy,我就不能得到代表原始列表的实际值。在

>>> np.percentile(B, 0.1)
15.02
>>> np.percentile(B, 0.2)
15.039999999999999
>>> np.percentile(B, 0.3)
15.06
>>> np.percentile(B, 0.4)
15.08
>>> np.percentile(B, 0.5)
15.1
>>> np.percentile(B, 0.6)
15.120000000000001
>>> np.percentile(B, 0.7)
15.140000000000001
>>> np.percentile(B, 0.8)
15.16
>>> np.percentile(B, 0.9)
15.18
>>> np.percentile(B, 1)
15.199999999999999
>>> np.percentile(B, 10)
17.0
>>> np.percentile(B, 20)
19.0
>>> np.percentile(B, 30)
23.0
>>> np.percentile(B, 40)
29.0
>>> np.percentile(B, 50)
35.0

我的问题是给定一个数组,如何通过使用线性插值技术计算百分位,从表示百分位(如10、20…100)的数组中获取值?


Tags: orgnumpyhttp列表returndefnpwiki
2条回答

纽比做的是对的。在

您的代码返回numList + [0]的百分位,即一个包含0的集合。在

第0个百分位项目将是numList中最低的项目,在示例中为15。在

我也有同样的问题。对我来说,这很简单。。。我认为百分位参数(你称之为P)是0.0-1.0的浮动,其中1.0代表100%百分位。在

我刚看了手册,发现p在0-100的范围内,100代表100%。在

numpy.percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear')

q : float in range of [0,100] (or sequence of floats) Percentile to compute which must be between 0 and 100 inclusive.

http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html

希望有帮助!在

相关问题 更多 >