简体   繁体   English

从 Pandas Dataframe 中删除值,从组的平均值中保持 1 STD

[英]Drop Values from Pandas Dataframe Groups of a Column keeping 1 STD from mean of Groups

on a Pandas df I want to drop rows on a column when its individual value is more or less 1 std from the mean of the group.在 Pandas df 上,当列的单个值与组的平均值相差或多或少 1 个标准时,我想在列上删除行。

For instance, I have a list of names related to an state, and I want to drop every instance that is above or below 1 std of price of the state.例如,我有一个与 state 相关的名称列表,我想删除高于或低于 state 价格标准的每个实例。

thx.谢谢。

#df
state price
a       10
a       30
a       60
b       60
b       50
...
n       x


stats = df.groupby('state')['price'].describe()


edit: thanks @MYousefi编辑:谢谢@MYousefi

but look my output, i still can see outliers on the second graph但看看我的 output,我仍然可以在第二张图上看到异常值

Ans1答案1

Edit2: problem solved with @MYousefi link below Edit2:问题通过下面的@MYousefi 链接解决

One way to do it is to calculate the deviation from the mean and select.一种方法是计算与平均值和 select 的偏差。

df = pd.DataFrame([['a', 10], ['a', 30], ['a', 60], ['b', 10], ['b', 50], ['b', 60]], columns = ['state', 'price'])

agg = df.groupby('state')['price'].agg(['mean', 'std'])

df[((df[['state', 'price']].set_index('state')['price'] - agg['mean']).abs() / agg['std']).reset_index(drop=True) <= 1]

The output of the last statement should be:最后一条语句的 output 应该是:

  state  price
0     a     10
1     a     30
4     b     50
5     b     60

Also found Pandas filter anomalies per group by Zscore which is the same thing I believe.还发现Pandas 按 Zscore 的每组过滤器异常,这与我相信的相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM