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

如何为Pandas DataFrame新增层级,层级来自另一DataFrame列?

按分类重组Pandas多层列索引

输入数据

data_df 结构

A             B             C               D
    a1 a2  a3     b1 b2 b3      c1 c2 c3        d1 d2 d3
1   1   2   3     5   6  7      3  4   5        10  1  8
2   0   5   4     8   7  9      1  5   7        8   6  1

universe_df 结构

Index Symbol Category
1       A       X
2       B       Y
3       C       Y
4       D       Z

期望输出

X                     Y                    Z
       A               B           C              D
    a1 a2  a3       b1 b2 b3    c1 c2 c3       d1 d2 d3
1   1  2   3         5  6  7     3 4   5        10 1  8
2   0  5   4         8  7  9     1  5  7         8 6  1

实现步骤

  1. 构建分类映射字典:从universe_df中提取Symbol到Category的对应关系
  2. 排序列顺序:根据分类和Symbol对data_df的列进行排序
  3. 重构多层列索引:将分类作为最顶层的列索引,形成三层结构

代码实现

import pandas as pd

# 假设已加载data_df和universe_df

# 步骤1:创建Symbol到Category的映射字典
cat_map = universe_df.set_index('Symbol')['Category'].to_dict()

# 步骤2:按分类、Symbol、子列排序data_df的列
sorted_columns = sorted(data_df.columns, key=lambda col: (cat_map[col[0]], col[0], col[1]))
sorted_df = data_df[sorted_columns]

# 步骤3:重构三层列索引
new_columns = pd.MultiIndex.from_tuples(
    [(cat_map[col[0]], col[0], col[1]) for col in sorted_columns],
    names=['Category', 'Symbol', 'SubCol']
)
result_df = sorted_df.copy()
result_df.columns = new_columns

# 查看结果
print(result_df)

说明

  • 排序时先按Category分组(X、Y、Z),再按Symbol(A、B、C、D)排序,最后按子列(a1、a2等)保持原有顺序
  • 重构列索引后,最终的DataFrame会呈现三层列结构,完全匹配期望输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:01:28