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

如何将energy_products透视为主列,使consumption_ktoe等成为其子列

问题描述

原始DataFrame结构如下:

year     energy_products  consumption_ktoe    value_ktoe
0   2009       Coal and Peat               3.0      3.300000
1   2009           Crude Oil               0.0  49079.900000
2   2009         Electricity            3338.1   3594.203691
3   2009         Natural Gas             867.8   6656.700000
4   2009              Others               0.0      0.000000
..  ...            .......           .......       .........

期望将energy_products作为顶层列,每个顶层列下包含consumption_ktoe和value_ktoe两个子列,输出结构示例:

energy_products  Coal and Peat                 Crude Oil                     \
    year          consumption_ktoe  value_ktoe  consumption_ktoe  value_ktoe
0   2009                       3.0    3.300000                 0       49079.9


energy_products   Electricity                   Natural Gas                   \
    year          consumption_ktoe  value_ktoe  consumption_ktoe  value_ktoe  
0   2009                    3338.1   3594.203691             867.8       6656.7

energy_products   Others
    year          consumption_ktoe  value_ktoe  
0   2009                       0.0        0.0 

尝试过以下方法但未达到预期:

  • 使用pivot(index='year', columns=['energy_products']):得到的是consumption_ktoe和value_ktoe作为顶层列,不符合需求
  • 使用swaplevel(axis=1):同类型子列被集中,仍不符合
  • 使用groupby:会自动聚合求和,不是想要的结果

需要实现无需聚合的列分组,得到期望的列结构。

解决方案

可以通过调整列层级顺序+重新排序列来实现需求,步骤如下:

  1. 先执行pivot操作,得到默认的层级列:
finalConImportMerge = finalConImportMerge.pivot(index='year', columns=['energy_products'])
  1. 交换列的层级,把energy_products放到顶层:
finalConImportMerge = finalConImportMerge.swaplevel(axis=1)
  1. 对列进行排序,让每个energy_products对应的两个子列(consumption_ktoe和value_ktoe)排在一起:
finalConImportMerge = finalConImportMerge.sort_index(axis=1)

或者可以一步完成:

finalConImportMerge = (finalConImportMerge
                       .pivot(index='year', columns=['energy_products'])
                       .swaplevel(axis=1)
                       .sort_index(axis=1))

这样处理后,列结构就会变成energy_products作为顶层,每个顶层列下依次排列consumption_ktoe和value_ktoe子列,完全符合需求,且不会触发聚合操作(因为year+energy_products是唯一标识,pivot本身不需要聚合)。

如果你的数据中year和energy_products存在重复组合,需要指定aggfunc为first或其他非聚合方式来保留原始数据,比如:

finalConImportMerge = (finalConImportMerge
                       .pivot(index='year', columns=['energy_products'], aggfunc='first')
                       .swaplevel(axis=1)
                       .sort_index(axis=1))

内容的提问来源于stack exchange,提问作者ACEZ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:55:16