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

Pandas中按CustomerID分组将用户购买商品合并为逗号分隔值的方法咨询

实现方案

你可以通过Pandas的分组聚合功能完成需求,核心代码如下:

import pandas as pd

# 构造测试数据
df_dict = {
    'CustomerID' : [1 , 2 , 3, 4, 1, 2, 3, 4],
    'Products_Purchased' : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
}
df = pd.DataFrame(df_dict)

# 按CustomerID分组,拼接对应产品字段为逗号分隔字符串
result = df.groupby('CustomerID', as_index=False)['Products_Purchased'].agg(', '.join)

补充说明

如果你的Products_Purchased字段存在非字符串类型的值,可以调整聚合逻辑避免报错:

result = df.groupby('CustomerID', as_index=False)['Products_Purchased'].agg(lambda x: ', '.join(x.astype(str)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:36:01