You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定列分组移除DataFrame中95百分位数以上的数据?

按分组移除95百分位数以上的数据

要实现按指定列分组后,移除每个分组内95百分位数以上的数据,你可以用Pandas的groupby结合transform或filter方法,两种方式都能满足需求:

方法一:使用groupby.transform

transform方法会将每个分组的计算结果匹配回原DataFrame的每一行,这样就能逐行判断是否符合分组内的筛选条件:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'type': ['A', 'A', 'A', 'B', 'B'],
    'value': [100000, 0.1, 0.3, 10, 11]
})

# 按type分组,计算每个分组的95%分位数,筛选出符合条件的行
filtered_df = df[df.groupby('type')['value'].transform(lambda x: x < x.quantile(0.95))]

方法二:使用groupby.filter

filter方法直接对每个分组进行筛选,只保留符合条件的分组行,逻辑更直观:

filtered_df = df.groupby('type').filter(lambda x: x['value'] < x['value'].quantile(0.95))

结果验证

针对你的示例数据:

  • A分组的95%分位数约为89999.73,因此100000会被过滤,保留0.1和0.3
  • B分组的95%分位数为10.95,因此11会被过滤,保留10

最终筛选后的DataFrame如下:

type  value
1    A    0.1
2    A    0.3
3    B   10.0

内容的提问来源于stack exchange,提问作者Thelonious Monk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:06:27