首页 > 解决方案 > 浮点范围的百分位数

问题描述

我正在编写一个函数,它采用浮点数列表并打印出浮点的“pth”百分位数:

from scipy import stats

def print_percentiles(a, p):
    for i in p:
        print('The ', i, 'th percentile is ', stats.scoreatpercentile(a, i), '.', sep='')

print_percentiles([1, 1, 3, 6, 2], [50])
# The 50th percentile is 2.0.

print_percentiles(range(1, 21), [75, 25])
# The 75th percentile is 15.25.
# The 25th percentile is 5.75.

我得到了第一次测试的正确输出,但是当函数的第一个参数是一个数字范围 (1, 21) 时,输出不正确,它应该是:

第 75 个百分位是 15.0。

第 25 个百分位是 5.0。

在这种情况下,为什么函数会产生错误的输出?

标签: pythonscipystatisticspercentile

解决方案


只需使用所需interpolation_method='lower'的,因为这不是文档中描述的默认值。

from scipy import stats

def print_percentiles(a, p):
    for i in p:
        print('The ', i, 'th percentile is ', stats.scoreatpercentile(a, i, interpolation_method='lower'), '.', sep='')

print_percentiles([1, 1, 3, 6, 2], [50])
# The 50th percentile is 2.0.

print_percentiles(range(1, 21), [75, 25])

结果:

The 50th percentile is 2.0.
The 75th percentile is 15.0.
The 25th percentile is 5.0.

推荐阅读