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

无需使用groupby函数,将Pandas DataFrame的Role按Value分组

不使用groupby实现Pandas按Value分组合并Role列

原始DataFrame构造

import pandas as pd

df = pd.DataFrame({
    'Value': ['A', 'A', 'A', 'B', 'B'],
    'Role': ['1', '2', '4', 'FD', 'XF']
})

解决方案(不使用groupby)

方法1:手动字典聚合

通过遍历DataFrame行,用字典存储每个Value对应的所有Role值,最后将字典转换为目标格式的DataFrame:

# 初始化字典存储分组后的Role数据
role_groups = {}
for value, role in df.itertuples(index=False):
    if value not in role_groups:
        role_groups[value] = []
    role_groups[value].append(role)

# 将字典转换为结果DataFrame,并用逗号连接Role列表
result_df = pd.DataFrame([
    {'Value': val, 'Role': ','.join(roles)} 
    for val, roles in role_groups.items()
])

方法2:使用pivot_table聚合

利用pivot_table的聚合能力,指定字符串连接作为聚合逻辑:

result_df = df.pivot_table(
    index='Value',
    values='Role',
    aggfunc=lambda x: ','.join(x)
).reset_index()

结果验证

执行代码后,result_df输出如下:

ValueRole
A1,2,4
BFD,XF

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:06:22