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

多列转置与重命名:DataFrame格式转换问题求助

问题描述

现有如下结构的DataFrame:

Product IdCategorymonthsalesprofit
xyxShoesFeb10001235
xyxShoesMarch12001455
abaBagsFeb140007235
abaBagsMarch52008455

需要实现半转置:每个唯一Product Id对应一行,新增feb_sales、march_sales、feb_profit、march_profit列,同时移除month列。

尝试过以下代码(及变体)但未成功:

table.values.reshape(1, -1), columns=table['month','sales','Profit']

期望得到的结果如下:

Product IdCategoryfeb salesfeb profitmarch salesmarch profit
xyxShoes1000123512001455
abaBags14000723552008455
解决方案

使用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]

代码说明:

  1. pivot参数设置:
    • index=['Product Id', 'Category']:指定这两列为行基准,保证每个唯一组合对应一行
    • columns='month':将month列的不同取值作为列的第二层索引
    • values=['sales', 'profit']:指定需要转置的数值字段
  2. reset_index():将行索引转换为普通列,恢复常规的DataFrame结构
  3. 列名重命名:把多层列索引(如('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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:57:35