【问题标题】:Flag outliers in the dataframe for each group标记每个组的数据框中的异常值
【发布时间】:2019-12-06 23:20:45
【问题描述】:

我想识别数据框中每组值的异常值,并返回一个数据框,其中包含数据框每一行的 True/False 列。

data = {'Group':['A', 'A', 'A', 'B', 'B', 'B'], 'Age':[20, 21, 19, 18, 2, 17]} 
df = pd.DataFrame(data) 

def flag_outlier(x):
    lower_limit  = np.mean(x) - np.std(x) * 3 
    upper_limit = np.mean(x) + np.std(x) * 3
    for i in x:
        if i > upper_limit or i < lower_limit:
            return True
df['Flag'] = df.groupby('Group')['Age'].apply(flag_outlier)

这段代码返回一个带有NaN的列,这个函数如何修复?

这篇文章 apply a function to a groupby function 类似,但我想不通。

非常感谢,

【问题讨论】:

    标签: python pandas apply pandas-groupby


    【解决方案1】:

    您可以使用groupby().transform分组获取meanstd,然后between查找异常值:

    groups = df.groupby('Group')
    means = groups.Age.transform('mean')
    stds = groups.Age.transform('std')
    
    df['Flag'] = df.Age.between(means-stds*3, means+stds*3)
    

    【讨论】:

    • @piRSquared 谢谢。
    • 异常值将带有“False”标志,对吗?
    • @Rod0n 是的。没错
    【解决方案2】:

    将您的功能更改为以下内容,

    def flag_outlier(x):
        lower_limit  = np.mean(x) - np.std(x) * 3 
        upper_limit = np.mean(x) + np.std(x) * 3
        return (x>upper_limit)| (x<lower_limit)
    

    因为你的处理方式,你的函数每组只返回一个值

    【讨论】:

    • 我接受了这个答案,因为它与我原来的解决方案更相似,但另一个答案也很棒。谢谢大家
    • 虽然我很欣赏你的观点,但更接近你的答案并不是衡量善良的标准......一般来说。另一个答案坚持使用现有的 pandas API,应该相当有效。这个答案很好,但在我看来,另一个更好。我写这篇文章是为了让所有可能查看此问题和答案的人受益。
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2021-11-17
    • 2021-03-26
    • 2015-06-21
    • 2011-09-18
    • 2019-06-24
    • 2015-07-06
    • 2017-07-01
    相关资源
    最近更新 更多