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

Pandas分组合并多字符串:DataFrame Type字段合并方法咨询

Pandas分组合并字段解决方案

直接上实用代码,两步就能搞定需求:

首先构造示例数据(和你给出的结构一致):

import pandas as pd

df = pd.DataFrame({
    'Source': ['A', 'A', 'B'],
    'Destination': ['B', 'B', 'C'],
    'Type': ['Insert', 'Delete', 'Insert']
})

然后执行分组合并操作:

# 按Source和Destination分组,用逗号连接同组内的Type字段值
result_df = df.groupby(['Source', 'Destination'])['Type'].agg(', '.join).reset_index()

运行后得到的result_df就是你想要的结果:

Source Destination           Type
0      A           B  Insert, Delete
1      B           C          Insert

核心逻辑:groupby指定分组的列,agg(', '.join)对每个分组里的Type列执行字符串拼接,最后用reset_index()把分组的索引变回普通列,恢复成标准的DataFrame结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:49:00