我有一个具有不同类别的数据框,并希望排除每个类别的给定百分位数以上的所有值。
d = {'cat': ['A', 'B', 'A', 'A', 'C', 'C', 'B', 'A', 'B', 'C'],
'val': [1, 2, 4, 2, 1, 0, 9, 8, 7, 7]}
df = pd.DataFrame(data=d)
cat val
0 A 1
1 B 2
2 A 4
3 A 2
4 C 1
5 C 0
6 B 9
7 A 8
8 B 7
9 C 7
因此,例如,排除0.95百分位应该导致:
cat val
0 A 1
1 B 2
2 A 4
3 A 2
4 C 1
5 C 0
8 B 7
因为我们有:
>>> df[df['cat']=='A'].quantile(0.95).item()
7.399999999999999
>>> df[df['cat']=='B'].quantile(0.95).item()
8.8
>>> df[df['cat']=='C'].quantile(0.95).item()
6.399999999999999
实际上有很多类别,我需要一个简洁的方法来做到这一点。
您可以将quantile
函数与groupby
结合使用:
df.groupby('cat')['val'].apply(lambda x: x[x < x.quantile(0.95)]).reset_index().drop(columns='level_1')
我提出了以下解决方案:
idx = [False] * df.shape[0]
for cat in df['cat'].unique():
idx |= ((df['cat']==cat) & (df['val'].between(0, df[df['cat']==cat ].quantile(0.95).item())))
df[idx]
但是看到其他解决方案(希望更好的解决方案)会很高兴。