如何基于指定列将pandas DataFrame的对应值横向并排展示
实现思路
核心是给同一A值分组下的多个B值生成位置序号,再将序号映射为新列,把对应B值放到对应列下即可实现横向展开,以下是两种常用实现方案:
方法1:pivot实现(可读性更高)
import pandas as pd # 构造原始数据 d = {'A': [0,1,2,3,4,0,1,2,3,4], 'B': [10,11,17,13,15,2,3,19,20,21]} df = pd.DataFrame(d) # 生成分组内的序号作为后续列的标识 df['col_idx'] = df.groupby('A').cumcount() # 透视转换得到横向展开结果 res = df.pivot(index='A', columns='col_idx', values='B').reset_index() # 重命名列符合要求 res.columns = ['A', 'D', 'E'] print(res)
方法2:groupby聚合列表拆分(代码更简洁)
无需新增临时列,直接聚合后拆分列表为多列:
res = df.groupby('A')['B'].agg(list).apply(pd.Series).reset_index() res.columns = ['A', 'D', 'E']
两种方法运行后均可得到你需要的输出结果:
A D E 0 0 10 2 1 1 11 3 2 2 17 19 3 3 13 20 4 4 15 21
内容的提问来源于stack exchange,提问作者Felipe Araya Olea
相关产品推荐
相关产品推荐

