排除不同类别百分位数以上的所有数据

问题描述 投票:0回答:2

我有一个具有不同类别的数据框,并希望排除每个类别的给定百分位数以上的所有值。

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

实际上有很多类别,我需要一个简洁的方法来做到这一点。

python pandas percentile
2个回答
1
投票

您可以将quantile函数与groupby结合使用:

df.groupby('cat')['val'].apply(lambda x: x[x < x.quantile(0.95)]).reset_index().drop(columns='level_1')

0
投票

我提出了以下解决方案:

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]  

但是看到其他解决方案(希望更好的解决方案)会很高兴。

© www.soinside.com 2019 - 2024. All rights reserved.