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
相关产品推荐
相关产品推荐

