gpt4 book ai didi

python - 使用 groupby 删除 Pandas 数据框中的异常值

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:32 25 4
gpt4 key购买 nike

我有一个报告日期、时间间隔和全年总量的数据框。我希望能够在每个时间间隔内删除异常值。

这是我所能得到的...

dft.head()

Report Date Time Interval Total Volume
5784 2016-03-01 24 467.0
5785 2016-03-01 25 580.0
5786 2016-03-01 26 716.0
5787 2016-03-01 27 803.0
5788 2016-03-01 28 941.0

所以我计算分位数的

low = .05
high = .95
dfq = dft.groupby(['Time Interval']).quantile([low, high])
print(dfq).head()

Total Volume
Time Interval
24 0.05 420.15
0.95 517.00
25 0.05 521.90
0.95 653.55
26 0.05 662.75

然后我希望能够使用它们在每个时间间隔内使用类似这样的方法删除异常值......

dft = dft.apply(lambda x: x[(x>dfq.loc[low,x.name]) & (x < dfq.loc[high,x.name])], axis=0)

最佳答案

一种方法是过滤掉如下:

In [11]: res = df.groupby("Date")["Interval"].quantile([0.05, 0.95]).unstack(level=1)

In [12]: res
Out[12]:
0.05 0.95
Date
2016-03-01 489.6 913.4

现在我们可以使用 loc 和过滤器为每一行查找这些值:

In [13]: (res.loc[df.Date, 0.05] < df.Interval.values) & (df.Interval.values < res.loc[df.Date, 0.95])
Out[13]:
Date
2016-03-01 False
2016-03-01 True
2016-03-01 True
2016-03-01 True
2016-03-01 False
dtype: bool

In [14]: df.loc[((res.loc[df.Date, 0.05] < df.Interval.values) & (df.Interval.values < res.loc[df.Date, 0.95])).values]
Out[14]:
Report Date Time Interval Total Volume
1 5785 2016-03-01 25 580.0 NaN
2 5786 2016-03-01 26 716.0 NaN
3 5787 2016-03-01 27 803.0 NaN

注意:按“时间间隔”分组的效果相同,但在您的示例中不会过滤任何行!

关于python - 使用 groupby 删除 Pandas 数据框中的异常值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47104072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com