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

如何在Pandas中按指定列表内的字段值分组数据?

Pandas按指定列表值分组的实现方法

原始数据

column1 column2 column3
1       14      P22
3       43      P65
4       43      141
3       14      146
5       43      P51

需求说明

将column3中值为141、146、P51的行归为一组,其余行归为另一组。

实现步骤

1. 构造DataFrame(已有数据可跳过)

import pandas as pd

data = {
    'column1': [1, 3, 4, 3, 5],
    'column2': [14, 43, 43, 14, 43],
    'column3': ['P22', 'P65', '141', '146', 'P51']
}
df = pd.DataFrame(data)

2. 定义目标分组列表

target_values = ['141', '146', 'P51']

3. 拆分得到两组数据

直接通过布尔索引筛选即可:

# 第一组:不在目标列表中的行
group1 = df[~df['column3'].isin(target_values)]
# 第二组:在目标列表中的行
group2 = df[df['column3'].isin(target_values)]

4. 查看结果

打印group1:

column1  column2 column3
0        1       14     P22
1        3       43     P65

打印group2:

column1  column2 column3
2        4       43     141
3        3       14     146
4        5       43     P51

若需使用groupby做后续操作

如果要基于分组执行聚合等操作,直接用groupby即可:

groups = df.groupby(df['column3'].isin(target_values))
# 遍历分组
for is_target, group_df in groups:
    print(f"{'目标组' if is_target else '非目标组'}:")
    print(group_df)
    print()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:52:11