Pandas实现按一列分组展平含两列的DataFrame
按cust_id分组后展平product列为多列
原始DataFrame
cust_id product 1 tv 1 phone 2 bat 2 ball 3 bat 4 ball 4 bat 4 tv 4 phone 5 tv 6 bat 7 bat 7 ball 7 tv 8 phone 8 tv
预期输出
cust_id 0 1 2 3 1 tv phone NaN NaN 2 bat ball NaN NaN 3 bat NaN NaN NaN 4 ball bat tv phone 5 tv NaN NaN NaN 6 bat NaN NaN NaN 7 bat ball tv NaN 8 phone tv NaN NaN
尝试代码(结果为单列含列表)
s = df.groupby(['cust_id'])['product'].apply(list)
正确实现方式
方式一:简洁版(直接展开列表为多列)
利用pd.Series将分组后的列表直接拆分为多列:
result = df.groupby('cust_id')['product'].apply(pd.Series)
方式二:分步可控版(生成列索引后透视)
先给每组内的行分配序号,再通过透视转换结构:
# 为每个客户的产品分配组内序号 df['col_index'] = df.groupby('cust_id').cumcount() # 透视生成多列格式 result = df.pivot(index='cust_id', columns='col_index', values='product') # 可选:将列名转为字符串类型(如需要0、1、2这类列名) result.columns = result.columns.astype(str) # 可选:将cust_id从索引转为普通列 # result = result.reset_index()
两种方法都能得到符合预期的DataFrame,按需选择即可。
内容的提问来源于stack exchange,提问作者Danish
相关产品推荐
相关产品推荐

