【问题标题】:How do you calculate interquartile range (IQR) correctly using Python?如何使用 Python 正确计算四分位距 (IQR)?
【发布时间】:2019-04-19 14:45:02
【问题描述】:

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

根据thisthisthis,我尝试了 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

我在解决方案中缺少什么?

任何线索将不胜感激。

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

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

    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 参数,了解有关该选项实际作用的更多信息。

    【讨论】:

      【解决方案2】:

      使用numpy.quantile:

      import numpy as np
      
      x = np.array([4.1, 6.2, 6.7, 7.1, 7.4, 7.4, 7.9, 8.1])
      q1_x = np.quantile(x, 0.25, interpolation='midpoint')
      q3_x = np.quantile(x, 0.75, interpolation='midpoint')
      print(q3_x - q1_x)
      

      输出:

      1.2000000000000002
      

      【讨论】:

        猜你喜欢
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 2022-07-14
        • 2020-12-15
        相关资源
        最近更新 更多