1.分位數計算案例
Ex1: Given a data = [6, 47, 49, 15, 42, 41, 7, 39, 43, 40, 36],求Q1, Q2, Q3, IQR
步驟:
1. 排序,從小到大排列data,data = [6, 7, 15, 36, 39, 40, 41, 42, 43, 47, 49]
2. 計算分位數的位置
3. 給出分位數
實例:
pos = (n+1)*p,n為數據的總個數,p為0-1之間的值
Q1的pos = (11 + 1)*0.25 = 3 (p=0.25) Q1=15
Q2的pos = (11 + 1)*0.5 = 6 (p=0.5) Q2=40
Q3的pos = (11 + 1)*0.75 = 9 (p=0.75) Q3=43
IQR = Q3 - Q1 = 28
代碼:
import math
def quantile_p(data, p):
pos = (len(data) + 1)*p
pos_integer = int(math.modf(pos)[1])
pos_decimal = pos - pos_integer
Q = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal
return Q
data = [6, 7, 15, 36, 39, 40, 41, 42, 43, 47, 49]
Q1 = quantile_p(data, 0.25)
print("Q1:", Q1)
Q2 = quantile_p(data, 0.5)
print("Q2:", Q2)
Q3 = quantile_p(data, 0.75)
print("Q3:", Q3)
計算方式二:
pos = 1+ (n-1)*p,n為數據的總個數,p為0-1之間的值
Q1的pos = 1 + (11 - 1)*0.25 = 3.5 (p=0.25) Q1=25.5
Q2的pos = 1 + (11 - 1)*0.5 = 6 (p=0.5) Q2=40
Q3的pos = 1 + (11 - 1)*0.75 = 8.5 (p=0.75) Q3=42.5
代碼:
import math
def quantile_p(data, p):
pos = 1 + (len(data)-1)*p
pos_integer = int(math.modf(pos)[1])
pos_decimal = pos - pos_integer
Q = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal
return Q
data = [6, 7, 15, 36, 39, 40, 41, 42, 43, 47, 49]
Q1 = quantile_p(data, 0.25)
print("Q1:", Q1)
Q2 = quantile_p(data, 0.5)
print("Q2:", Q2)
Q3 = quantile_p(data, 0.75)
print("Q3:", Q3)
示例2:
import math
def quantile_p(data, p):
data.sort()
pos = (len(data) + 1)*p
pos_integer = int(math.modf(pos)[1])
pos_decimal = pos - pos_integer
Q = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal
return Q
data = [7, 15, 36, 39, 40, 41]
Q1 = quantile_p(data, 0.25)
print("Q1:", Q1)
Q2 = quantile_p(data, 0.5)
print("Q2:", Q2)
Q3 = quantile_p(data, 0.75)
print("Q3:", Q3)
計算結果:
Q1 = 7 +(15-7)×(1.75 - 1)= 13
Q2 = 36 +(39-36)×(3.5 - 3)= 37.5
Q3 = 40 +(41-40)×(5.25 - 5)= 40.25
分位數計算法二:
結果:
Q1: 20.25
Q2: 37.5
Q3: 39.75
2. 分位數解釋
概念:把給定的亂序數值由小到大排列並分成四等份,處於三個分割點位置的數值就是四分位數。
第1四分位數 (Q1),又稱“較小四分位數”,等於該樣本中所有數值由小到大排列后第25%的數字。
第2四分位數 (Q2),又稱“中位數”,等於該樣本中所有數值由小到大排列后第50%的數字。
第3四分位數 (Q3),又稱“較大四分位數”,等於該樣本中所有數值由小到大排列后第75%的數字。
四分位距(InterQuartile Range, IQR)= 第3四分位數與第1四分位數的差距
確定p分位數位置的兩種方法
position = (n+1)*p
position = 1 + (n-1)*p
利用pandas求
import pandas as pd
import numpy as np
dt = pd.Series(np.array([6, 47, 49, 15, 42, 41, 7, 39, 43, 40, 36])
print("數據格式:")
print(dt)
print('Q1:', df.quantile(0.25))
print('Q2:', df.quantile(0.5))
print('Q3:', df.quantile(0.75))
3.去噪
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
#解決亂碼和負值的負號不出現問題
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# 使顯示圖標自適應
mpl.rcParams['figure.autolayout'] = True
#包裝了一個異常值處理的代碼,可以調用
def outliers_proc(data, col_name, scale=3):
"""
用於清洗異常值,默認box_plot(scale=3)進行清洗
param data: 接收pandas數據格式
param col_name: pandas列名
param scale: 尺度
"""
def box_plot_outliers(data_ser, box_scale):
"""
利用箱線圖去除異常值
:param data_ser: 接收 pandas.Series 數據格式
:param box_scale: 箱線圖尺度
"""
iqr = box_scale * (data_ser.quantile(0.75) - data_ser.quantile(0.25))
val_low = data_ser.quantile(0.25) - iqr
val_up = data_ser.quantile(0.75) + iqr
rule_low = (data_ser < val_low)
rule_up = (data_ser > val_up)
return (rule_low,rule_up),(val_low,val_up)
data_n = data.copy()
data_serier = data_n[col_name]
rule, value = box_plot_outliers(data_serier,box_scale=scale)
index = np.arange(data_serier.shape[0])[rule[0]|rule[1]]
print("Delete number is:{}".format(len(index)))
data_n = data_n.drop(index)
data_n.reset_index(drop=True, inplace=True)
print("Now column number is:{}".format(data_n.shape[0]))
index_low = np.arange(data_serier.shape[0])[rule[0]]
outliers = data_serier.iloc[index_low]
print("Description of data less than the lower bound is:")
print(pd.Series(outliers).describe())
index_up = np.arange(data_serier.shape[0])[rule[1]]
outliers = data_serier.iloc[index_up]
print("Description of data larger than the upper bound is:")
print(pd.Series(outliers).describe())
fig, ax = plt.subplots(1,2, figsize=(10,7))
sns.boxplot(y=data[col_name],data=data,palette="Set1",ax=ax[0])
sns.boxplot(y=data_n[col_name],data=data_n,palette="Set1",ax=ax[1])
return data_n
