python - 如何使用 Python 正确计算四分位距 (IQR)?

标签 python numpy scipy

我正在尝试了解计算 iqr(四分位数间距)的方法。

根据 this , thisthis ,我尝试了 3 种解决方案来做到这一点。

解决方案_1

a = numpy.array([1, 2, 3, 4, 5, 6, 7])
q1_a = numpy.percentile(a, 25)
q3_a = numpy.percentile(a, 75)
q3_a - q1_a

解决方案_2

from scipy.stats import iqr
iqr(a)

解决方案_3

q1_am = np.median(numpy.array([1, 2, 3, 4]))
q3_am = np.median(numpy.array([4, 5, 6, 7]))
q3_am - q1_am

其中 3 个给出相同的结果,其中 3 个是正确的。

当我尝试另一组数字时,事情变得很奇怪。

solution_1 和 2 都输出 0.95,这是不正确的。

x = numpy.array([4.1, 6.2, 6.7, 7.1, 7.4, 7.4, 7.9, 8.1])
q1_x = numpy.percentile(x, 25)
q3_x = numpy.percentile(x, 75)
q3_x - q1_x

solution_3 给出的 1.2 是正确的

q1_xm = np.median(np.array([4.1, 6.2, 6.7,7.25]))
q3_xm = np.median(np.array([7.25,7.4, 7.9, 8.1]))
q3_xm - q1_xm

我在解决方案中遗漏了什么?

任何线索将不胜感激。

最佳答案

您将通过 numpy.percentile 获得预期的结果如果您设置 interpolation=midpoint:

x = numpy.array([4.1, 6.2, 6.7, 7.1, 7.4, 7.4, 7.9, 8.1])
q1_x = numpy.percentile(x, 25, interpolation='midpoint')
q3_x = numpy.percentile(x, 75, interpolation='midpoint')
print(q3_x - q1_x)

这个输出:

1.2000000000000002

设置 interpolation=midpoint 也会使 scipy.stats.iqr给出你想要的结果:

from scipy.stats import iqr

x = numpy.array([4.1, 6.2, 6.7, 7.1, 7.4, 7.4, 7.9, 8.1])
print(iqr(x, rng=(25,75), interpolation='midpoint'))

哪些输出:

1.2000000000000002

请参阅链接文档中的 interpolation 参数,了解有关该选项实际作用的更多信息。

关于python - 如何使用 Python 正确计算四分位距 (IQR)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53337391/

相关文章:

python - 生成器与列表理解

python - 将一个 numpy 列拆分为两列并将它们保留在原始数组中

python - 将 float 组渲染为 24 位 RGB 图像(例如使用 PIL)

optimization - 对大数据集进行曲线拟合

python - scipy.optimize.least_squares 是确定性的吗?

python - 在 Python 中构建协方差矩阵

python - Plotly:将等高线图更改为 3 维曲面

python - Qt 调试器在 mac 上使用错误的 python 版本

python - 向空 NumPy 数组添加新列

python - Numba 中的稀疏矩阵