Python从数据中删除异常值 [英] Python remove outliers from data

查看:3368
本文介绍了Python从数据中删除异常值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框如下:

ID Value
A   70
A   80
B   75
C   10
B   50
A   1000
C   60
B   2000
..  ..

我想按ID对数据进行分组,从分组数据(我们从箱线图中看到的)中删除离群值,然后计算均值.

I would like to group this data by ID, remove the outliers from the grouped data (the ones we see from the boxplot) and then calculate mean.

到目前为止

grouped = df.groupby('ID')

statBefore = pd.DataFrame({'mean': grouped['Value'].mean(), 'median': grouped['Value'].median(), 'std' : grouped['Value'].std()})

如何找到异常值,将其删除并获取统计信息.

推荐答案

我相信您所指的方法是删除> 1.5 *四分位数范围内的值.因此,首先,计算您的初始统计数据:

I believe the method you're referring to is to remove values > 1.5 * the interquartile range away from the median. So first, calculate your initial statistics:

statBefore = pd.DataFrame({'q1': grouped['Value'].quantile(.25), \
'median': grouped['Value'].median(), 'q3' : grouped['Value'].quantile(.75)})

然后确定原始DF中的值是否是离群值:

And then determine whether values in the original DF are outliers:

def is_outlier(row):
    iq_range = statBefore.loc[row.ID]['q3'] - statBefore.loc[row.ID]['q1']
    median = statBefore.loc[row.ID]['median']
    if row.Value > (median + (1.5* iq_range)) or row.Value < (median - (1.5* iq_range)):
        return True
    else:
        return False
#apply the function to the original df:
df.loc[:, 'outlier'] = df.apply(is_outlier, axis = 1)
#filter to only non-outliers:
df_no_outliers = df[~(df.outlier)]

这篇关于Python从数据中删除异常值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆