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

如何基于指定列将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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:48:04