【问题标题】:groupby operation in pandas.DataFrame without outliers没有异常值的 pandas.DataFrame 中的 groupby 操作
【发布时间】:2021-12-16 15:03:41
【问题描述】:

对于 pandas.Series,我知道如何去除异常值。像这样:

x = pd.Series(np.random.normal(size=1000))
iqr = x.quantile(.75) - x.quantile(.25)
y = x[x.between(x.quantile(.25) - 1.5*iqr, x.quantile(.75) + 1.5*iqr)]

我想对 DataFrame 的不同系列/列进行细化

import string
import random

df = pd.DataFrame([])
df['A'] = pd.Series(np.random.normal(size=1000))
df['B'] = pd.Series(np.random.normal(size=1000, loc=-5, scale=1))
df['C'] = pd.Series(np.random.normal(size=1000, loc=10, scale=2))
df['index'] = pd.Series([random.choice(string.ascii_uppercase) for i in range(1000)])

df.set_index('index')

我通常会做类似的事情

df = df.groupby('index').mean()

但是,在这种情况下,它也会对异常值进行平均,我想在平均时忽略它们。

请注意,随机数据比异常值在每列中的位置不同。因此,应仅在该列/系列中忽略异常值

结果应该是一个 DataFrame,有 26 行(index 的每个字母一个)和 3 列,其中的值是没有异常值的平均值

我可以遍历df 的列并执行第一段代码。但是有更好的方法吗?

欢迎提出建议。任何方法都可以接受

【问题讨论】:

  • 你想要的是计算没有异常值的每一列的平均值。我说的对吗?
  • 没错。为什么我很难用简单的方式来表达它?

标签: python pandas group-by outliers iqr


【解决方案1】:

使用以下代码。

def mean_without_outlier(x): # x: series
    iqr = x.quantile(.75) - x.quantile(.25)
    y = x[x.between(x.quantile(.25) - 1.5*iqr, x.quantile(.75) + 1.5*iqr)]
    return y.mean()

df.groupby("index")[['A', 'B', 'C']].agg(mean_without_outlier)

【讨论】:

  • 太棒了。感谢您指出最后一行,这是我所缺少的。我实际上做了df.groupby("index").agg(mean_without_outlier) 计算所有列/系列的过滤平均值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多