如何根据百分位数从组中去除异常值

4
我有一个表格df,类似于这样,但更长且具有许多其他type值。
type weight
a 35.1
a 36.7
b 100.2
b 99.3
b 102.0
b 5.0
a 38.2
a 250.8
我想用95th百分位数从df中删除所有异常值,但要将其拆分为type列中的单个值。
对于单个type值,我可以像这样操作:
my_perc = 95
temp = df[df['type'] == 'a']
temp[temp.weight < np.percentile(temp.weight, my_perc)]

现在我想自动处理整个表格 df,并考虑到类型列中的各个组。

我也尝试了以下代码:

df[df.groupby(['type'])['weight'] < np.percentile(df.weight, my_perc)]

但是它不起作用。

你有什么想法吗?

2个回答

3

好的,问题可能解决了:

my_perc = 0.95
df[df.groupby('type')['weight'].transform(lambda x : x < x.quantile(my_perc))]

1
你做对了,就是这样。但是你需要在 my_perc 之间传递0到1的值,现在它是 95,请改为 0.95 - ThePyGuy

0
你可以使用 DataFrame.groupby 对数据框按照 type 进行分组,然后使用 np.percentile 计算每个组的 weight 列的百分位数,以获得所需的结果。
df.groupby('type')['weight'].apply(lambda x:x[x.le(np.percentile(x, 95))]).droplevel(axis=0, level=1).reset_index()
  type  weight
0    a    35.1
1    a    36.7
2    a    38.2
3    b   100.2
4    b    99.3
5    b     5.0

1
这个回答在“低质量回答队列”中。 - moken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接