利用图基Tukey method检测数据集中的异常值

在数据集中如果某一个观察值不寻常地大于或者小于该数据集中的其他数据,我们则称之为疑似异常值。疑似异常值的存在,会对随后的计算结果产生不适当的影响,检测疑似异常值并加以适当的处理是十分必要的。

一种经典的计算数据集中疑似异常值的方法是Tukey method。该方法先计算出数据集的四分之一分位数(Q1)和四分之三分位数(Q3),从而计算出四分位数间距(IQR),然后将小于Q1 - 1.5IQR或者大于Q3 + 1.5IQR的数据点当做是疑似异常值。我们可以借助这种方法在DataFrame中检测异常值。代码如下:

import numpy as np
import pandas as pd
from collections import Counter
import matplotlib as plt


# Outlier detection
def detect_outliers(df, n, features):
    """
    Takes a dataframe df of features and returns a list of the indices
    corresponding to the observations containing more than n outliers according
    to the Tukey method.
    """
    outlier_indices = []

    # iterate over features(columns)
    for col in features:
        # 1st quartile (25%)
        Q1 = np.percentile(df[col], 25)
        # 3rd quartile (75%)
        Q3 = np.percentile(df[col], 75)
        # quartile spacing (IQR)
        IQR = Q3 - Q1
        # outlier step
        outlier_step = 1.5 * IQR

        # Determine a list of indices of outliers for feature col
        outlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step)].index

        # append the found outlier indices for col to the list of outlier indices
        outlier_indices.extend(outlier_list_col)

    # select observations containing more than n outliers
    outlier_indices = Counter(outlier_indices)
    multiple_outliers = list(k for k, v in outlier_indices.items() if v > n)

    return multiple_outliers


iris = pd.read_csv('./iris.csv', usecols=[0, 1, 2, 3])

print(detect_outliers(iris, 1, iris.columns))

利用iris.csv数据集,手动添加异常点:

40,44,45,46,setosa
77,55,33,44,setosa
99,88,82,123,setosa

运行上面的程序,可以将异常值找出来。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值