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

如何交换Pandas DataFrame列的Level 0与Level 1层级?

交换DataFrame列的层级顺序

初始代码:

import pandas as pd

df = pd.DataFrame({'serial':[1,2,3,4,5,6,1,2,3,4,5,6,7,1,2,3],
       'lot':['a','a','a','a','a','a','b','b','b','b','b','b','b','c','c','c'],
       'part':['aa','ab','ac','ad','ae','af','ba','bb','bc','bd','be','bf','bg','ca','cb','cc'],
       'qty':[1,2,1,3,1,5, 2,3,4,5,3,2,1,2,3,3]})

执行df.pivot(index='serial', columns='lot')后,列的层级结构为Level 0:part/qty,Level 1:a/b/c,要交换两个层级让a/b/c成为Level 0,part/qty成为Level 1,可以用以下两种方法:

方法1:用swaplevel交换层级

swaplevel专门用于交换MultiIndex的两个层级,配合sort_index整理列顺序,确保同一批次(lot)的字段集中排列:

df1 = df.pivot(index='serial', columns='lot')
# 交换列的两个层级(axis=1指定操作列)
df1_swapped = df1.swaplevel(axis=1)
# 按Level 0排序,让同一lot下的part和qty列连续
df1_swapped = df1_swapped.sort_index(axis=1)

方法2:用reorder_levels指定层级顺序

如果需要更灵活的层级排序(比如多于两个层级的场景),可以用reorder_levels指定层级的位置顺序,同样搭配sort_index:

df1_swapped = df.pivot(index='serial', columns='lot').reorder_levels([1, 0], axis=1).sort_index(axis=1)

验证结果

执行print(df1_swapped.columns)会输出整理后的列层级:

MultiIndex([('a', 'part'),
            ('a', 'qty'),
            ('b', 'part'),
            ('b', 'qty'),
            ('c', 'part'),
            ('c', 'qty')],
           names=['lot', None])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:52:45