多列转置与重命名:DataFrame格式转换问题求助
问题描述
现有如下结构的DataFrame:
| Product Id | Category | month | sales | profit |
|---|---|---|---|---|
| xyx | Shoes | Feb | 1000 | 1235 |
| xyx | Shoes | March | 1200 | 1455 |
| aba | Bags | Feb | 14000 | 7235 |
| aba | Bags | March | 5200 | 8455 |
需要实现半转置:每个唯一Product Id对应一行,新增feb_sales、march_sales、feb_profit、march_profit列,同时移除month列。
尝试过以下代码(及变体)但未成功:
table.values.reshape(1, -1), columns=table['month','sales','Profit']
期望得到的结果如下:
| Product Id | Category | feb sales | feb profit | march sales | march profit |
|---|---|---|---|---|---|
| xyx | Shoes | 1000 | 1235 | 1200 | 1455 |
| aba | Bags | 14000 | 7235 | 5200 | 8455 |
解决方案
使用pandas的pivot方法可以直接实现需求,步骤如下:
import pandas as pd # 假设你的DataFrame名为table result = table.pivot( index=['Product Id', 'Category'], columns='month', values=['sales', 'profit'] ).reset_index() # 重命名列名,转换成目标格式 result.columns = [f'{col[1].lower()}_{col[0]}' if col[1] else col[0] for col in result.columns]
代码说明:
pivot参数设置:index=['Product Id', 'Category']:指定这两列为行基准,保证每个唯一组合对应一行columns='month':将month列的不同取值作为列的第二层索引values=['sales', 'profit']:指定需要转置的数值字段
reset_index():将行索引转换为普通列,恢复常规的DataFrame结构- 列名重命名:把多层列索引(如
('sales', 'Feb'))转换成feb_sales的格式,匹配需求
如果你的数据存在重复的(Product Id, Category, month)组合,推荐用pivot_table(自动聚合重复项):
result = pd.pivot_table( table, index=['Product Id', 'Category'], columns='month', values=['sales', 'profit'], aggfunc='first' # 无重复数据时用first,有重复可换sum/mean等聚合方式 ).reset_index() # 同样重命名列名 result.columns = [f'{col[1].lower()}_{col[0]}' if col[1] else col[0] for col in result.columns]
内容的提问来源于stack exchange,提问作者milo204
相关产品推荐
相关产品推荐

