时间:2019.03.10
四分位数:四分位数(Quartile),也称四分位点,是指把一组数据中的所有数值由小到大排列并分成四等份时,处于三个分割点位置的数值。多应用于箱线图的绘制。
四分位数有三个,第一个四分位数称为下四分位数,第二个四分位数就是中位数,第三个四分位数称为上四分位数,分别用Q1、Q2、Q3表示。
统计学解释
四分位数位置的确定方法有两种。其一是Excel函数QUARTILE.EXC
的方法,也就是SPSS中使用的方法,其确定方法如下:
位 置 Q 1 = ( n + 1 ) × 0.25 位置_{Q1}=(n+1)\times0.25 位置Q1=(n+1)×0.25
位 置 Q 2 = ( n + 1 ) × 0.5 位置_{Q2}=(n+1)\times0.5 位置Q2=(n+1)×0.5
位 置 Q 3 = ( n + 1 ) × 0.75 位置_{Q3}=(n+1)\times0.75 位置Q3=(n+1)×0.75
其中 n n n为样本量
其二是Excel函数QUARTILE.INC
的方法,其确定方法如下:
位 置 Q 1 = 1 + ( n − 1 ) × 0.25 位置_{Q1}=1+(n-1)\times0.25 位置Q1=1+(n−1)×0.25
位 置 Q 2 = 1 + ( n − 1 ) × 0.5 位置_{Q2}=1+(n-1)\times0.5 位置Q2=1+(n−1)×0.5
位 置 Q 3 = 1 + ( n − 1 ) × 0.75 位置_{Q3}=1+(n-1)\times0.75 位置Q3=1+(n−1)×0.75
其中 n n n为样本量
我们以如下一组数据作为例子:1,2,3,4,5,6,7,8,9,10,11,12;
用第一种方法确定的四分位数位置分别为3.25,6.5,9.75;用第二种方法确定的四分位数位置分别为3.75、6.5、9.25。
在四分位数确定位置之后,四分位数的值为四分位数所在位置到前后项的距离的加权平均数。例如,第一四分位数的位置为3.25,则此时第一四位分数等于:
Q 1 = X 3 × ( 4 − 3.25 ) + X 4 × ( 3.25 − 3 ) Q1=X_3\times(4-3.25)+X_4\times(3.25-3) Q1=X3×(4−3.25)+X4×(3.25−3)
其中 X 3 X_3 X3为这组数据按大小排序的第3项, X 4 X_4 X4为这组数据按大小排序的第4项
实现思路
如果要通过以上计算方式在确定四分位数的位置后得到四分位数的值,则需要进行多步的判断和计算,因此我们不妨通过将四分位数位置的整数部分和小数部分分开计算来获取四分位数的值,即用如下的公式代替上面的公式:
Q n = X i + ( X i + 1 − X i ) × J Q_n=X_i+(X_{i+1}-X_i)\times{J} Qn=Xi+(Xi+1−Xi)×J
其中 Q n Q_n Qn为四分位数, i i i为四分位数位置的整数部分, j j j为四分位数位置的小数部分
实现代码
data_test=[1,2,3,4,5,6,7,8,9,10,11,12] # 定义测试数据
计算四分位数方法一(Excel的QUARTILE.EXC方法)
import math
def quantile_exc(data, n): # 其中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
测试
print("第1四分位数",quantile_exc(data_test, 1))
print("第2四分位数",quantile_exc(data_test, 2))
print("第3四分位数",quantile_exc(data_test, 3))
结果
第1四分位数 3.25
第2四分位数 6.5
第3四分位数 9.75
计算四分位数方法二(Excel的QUARTILE.INC方法)
import math
def quantile_inc(data, n): # 其中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("第1四分位数",quantile_inc(data_test, 1))
print("第2四分位数",quantile_inc(data_test, 2))
print("第3四分位数",quantile_inc(data_test, 3))
结果
第1四分位数 3.75
第2四分位数 6.5
第3四分位数 9.25
调用numpy的percentile方法计算四分位数
import numpy
print('第1四分位数',numpy.percentile(data_test, (25)))
print('第2四分位数',numpy.percentile(data_test, (50)))
print('第3四分位数',numpy.percentile(data_test, (75)))
结果
第1四分位数 3.75
第2四分位数 6.5
第3四分位数 9.25
代码解释
x=math.modf(i)
获取i的整数位整数位和小数位,其中x[0]为小数位,x[1]为整数位