pandas如何将同组多行合并为单行并新增列存储额外信息
实现方案
你可以通过给分组内的行添加序号,再拆堆(unstack)的方式实现多列场景下的行转列,完整代码如下:
import pandas as pd rankings = {'Team': ['A', 'A', 'B', 'B', 'C', 'C', 'C'], 'Description': ['Aggressive', 'Strong', 'Passive', 'Strong', 'Bad', 'Loser Streak', 'Injured'], 'Description Continued': ['Aggressive ...', 'Strong ...', 'Passive ...', 'Strong ...', 'Bad ...', 'Loser Streak ...', 'Injured ...']} rankings_pd = pd.DataFrame(rankings) # 给每个Team内的行标注顺序序号 rankings_pd['row_idx'] = rankings_pd.groupby('Team').cumcount() + 1 # 行转列操作 result = rankings_pd.set_index(['Team', 'row_idx']).unstack('row_idx') # 扁平化处理多级列名 result.columns = [f'{col_name[0]}_{col_name[1]}' for col_name in result.columns] # 重置索引将Team恢复为普通列 result = result.reset_index() print(result)
输出结果说明
运行后得到的result结构符合预期:
- 每个Team仅保留一行
- 不同序号的Description和Description Continued会自动生成带数字后缀的新列,比如
Description_1、Description_2、Description Continued_1等 - 行数少的Team对应的多余列值自动填充为NaN
替代方案(适配pandas 1.1.0及以上版本)
你也可以直接用pivot方法实现,无需手动设置索引:
rankings_pd['row_idx'] = rankings_pd.groupby('Team').cumcount() + 1 result = rankings_pd.pivot(index='Team', columns='row_idx') result.columns = [f'{c[0]}_{c[1]}' for c in result.columns] result = result.reset_index()
内容的提问来源于stack exchange,提问作者hsnsd
相关产品推荐
相关产品推荐

