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

Pandas按'A'分组后筛选包含全部指定C值的分组及对应行

Pandas分组筛选解决方案

没问题,我来帮你搞定这两个Pandas分组筛选的需求!先看一下我们的原始数据:

import pandas as pd

df = pd.DataFrame({
    'A' : ['bar', 'bar', 'bar', 'foo', 'foo', 'foo'],
    'B' : [1, 2, 3, 4, 5, 6],
    'C' : [2.0, 5., 8., 1., 2., 9.]
})
print(df)

输出结果:

A  B    C
0  bar  1  2.0
1  bar  2  5.0
2  bar  3  8.0
3  foo  4  1.0
4  foo  5  2.0
5  foo  6  9.0

需求1:获取C列同时包含neededVals = [1.0,2.0]的分组

我们可以用groupby结合filter方法来实现,filter会保留所有满足条件的整个分组。核心思路是检查每个分组的C列是否包含neededVals里的所有值:

neededVals = [1.0, 2.0]

# 筛选出C列同时包含所有指定值的分组
filtered_groups = df.groupby('A').filter(lambda x: all(val in x['C'].values for val in neededVals))
print(filtered_groups)

输出结果:

A  B    C
3  foo  4  1.0
4  foo  5  2.0
5  foo  6  9.0

需求2:获取上述分组中仅包含C列为指定值的行

拿到需求1的结果后,我们可以用isin方法筛选出C列属于neededVals的行:

# 在筛选后的分组中保留C列符合指定值的行
target_rows = filtered_groups[filtered_groups['C'].isin(neededVals)]
print(target_rows)

输出结果:

A  B    C
3  foo  4  1.0
4  foo  5  2.0

如果你想一步完成两个操作,也可以把代码合并:

target_rows = df.groupby('A').filter(lambda x: all(val in x['C'].values for val in neededVals))
target_rows = target_rows[target_rows['C'].isin(neededVals)]

这样就能完美得到你想要的结果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:57:47