0
点赞
收藏
分享

微信扫一扫

统计学的Python实现-010:四分位距



时间:2019.03.10


四分位距:四分位距(interquartile range),是一种衡量一组数据离散程度的统计量,用IQR表示。其值为第一四分位数和第三四分位数的差距。

四分位距的计算公式如下:

其中 为第一四分位数, 为第三四分位数

实现代码

import math
data_test=[1,2,3,4,5,6,7,8,9,10,11,12] # 定义测试数据

#四分位数计算方法一(相当于Excel的QUARTILE.EXC方法)
def quantile_exc(data, n):
if n<1 or n>3:
return false
data.sort()
position = (len(data) + 1)*n/4
pos_integer = int(math.modf(position)[1])
pos_decimal = position - pos_integer
quartile = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal
return quartile

#四分位数计算方法二(相当于Excel的QUARTILE.INC方法)
def quantile_inc(data, n):
if n<1 or n>3:
return false
data.sort()
position = 1 + (len(data)-1)*n/4
pos_integer = int(math.modf(position)[1])
pos_decimal = position - pos_integer
quartile = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal
return quartile

# 测试
print('IQR(1) =',quantile_exc(data_test,3)-quantile_exc(data_test,1))
print('IQR(2) =',quantile_inc(data_test,3)-quantile_inc(data_test,1))

结果



举报

相关推荐

0 条评论