分位数介绍

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

 

posted @ 2020-12-31 16:55  1直在路上1  阅读(2012)  评论(0编辑  收藏  举报