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

