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

Pandas将name列值转为新列并合并同match_id行的实现方法

解决方案

你已经提前完成数据聚合、不存在match_id+name重复值的场景下,不需要用pivot_table,直接用更轻量的pivot方法或者set_index+unstack组合就可以快速实现转换,不会触发额外的聚合运算,效率更高。

方案1:直接用pivot方法(最简便)

# 指定分组索引、待展开的列、填充值
res = df.pivot(
    index=['team1', 'team2', 'match_id'],
    columns='name',
    values=['counts_team1', 'counts_team2']
)
# 拼接生成你要求格式的新列名
res.columns = [f"{col[1]}_{col[0]}" for col in res.columns]
# 把索引列重置为普通列
res = res.reset_index()

方案2:set_index + unstack 组合(逻辑更直观)

res = df.set_index(['team1', 'team2', 'match_id', 'name']).unstack('name')
res.columns = [f"{col[1]}_{col[0]}" for col in res.columns]
res = res.reset_index()

内容的提问来源于stack exchange,提问作者8-Bit Borges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:54:04