天天看點

boxplot 箱線圖剔除離群值

這是天池的一個代碼,拿來主義直接用

import seaborn as sns
import pandas as pd

# 包裝了一個異常值處理的代碼,可以調用
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

           
cls = [2, 2, 25119, 6, 4, 7, 3, 47, 11, 24, 5, 16, 11, 19, 9, 4, 5, 6, 2, 16, 1, 1, 2, 10, 14, 22, 2751, 16, 11, 10, 2, 1, 18, 8, 13, 7, 4, 5, 12, 13, 1, 7, 9502, 3, 34, 5, 3, 1, 1, 7, 29, 2, 1, 14, 15, 1, 8]

data = pd.DataFrame(cls, columns=['dis_num'])
data = outliers_proc(data, 'dis_num', scale=10)
plt.show()
           
boxplot 箱線圖剔除離群值
boxplot 箱線圖剔除離群值

繼續閱讀