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

如何拆堆Pandas DataFrame,使Level 0索引位于列层级上方?

Pandas多级索引DataFrame列层级调整问题

问题背景

现有一个名为info的Pandas DataFrame,多级索引为['symbol','date'],数据结构如下:

Symbol   date            Sector      Industry
a        2022-01-01       2             6
         2022-01-02       3             7
b        2022-01-02       4             8
         2022-01-03       5             9

期望得到的DataFrame结构如下:

a                      b 
                sector  industry    sector  industry
2022-01-01         2       6          NaN     NaN
2022-01-02         3       7           4       8
2022-01-03         NaN     NaN         5       9

尝试使用info.unstack(level=0)拆堆后,得到的结果列层级不符合预期:

sector                  industry   
date            a      b               a          b
2022-01-01      2      NaN             6        NaN
2022-01-02      3      4               7          8
2022-01-03      NaN    5               NaN        9

需要调整列层级,让symbol(a、b)位于sector和industry的上方。

解决方案

你可以通过swaplevel()交换列的层级顺序,再用sort_index()对列进行排序,就能得到目标结构:

# 执行拆堆操作
df_unstacked = info.unstack(level=0)
# 交换列的两个层级,并按层级排序
df_result = df_unstacked.swaplevel(axis=1).sort_index(axis=1)

说明

  • swaplevel(axis=1):针对列(axis=1)交换多级索引的两个层级,将原本位于下层的symbol移到上层,原上层的Sector/Industry移到下层。
  • sort_index(axis=1):对列索引进行排序,确保同一个symbol对应的sector和industry列相邻排列,符合目标格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:45:45