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

如何将DataFrame对比生成的多级列索引结果扁平化为指定结构?

多级列索引DataFrame扁平化适配Dash AG Grid的高效实现

直接操作列索引进行层级拼接是最高效的方式——不需要对DataFrame的行数据做任何转换,性能最优,尤其适合大数据量场景。

核心代码实现

# 将多级列索引的每一层用下划线拼接成单级列名
res.columns = res.columns.map('_'.join)

完整示例流程

  1. 先构造测试用的DataFrame并生成对比结果:
import pandas as pd

dfA = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
dfB = pd.DataFrame({'col1': [1, 7, 3], 'col2': [8, 5, 9]})

# 生成带多级列索引的对比结果
res = dfA.compare(dfB, keep_equal=True, keep_shape=True).rename(columns={'self': 'A', 'other': 'B'}, level=-1)

此时res的列结构是多级索引:[('col1', 'A'), ('col1', 'B'), ('col2', 'A'), ('col2', 'B')]

  1. 执行扁平化操作后:
res.columns = res.columns.map('_'.join)

res的列会变成单级结构:['col1_A', 'col1_B', 'col2_A', 'col2_B'],完全符合Dash AG Grid的要求。

自定义分隔符

如果需要用其他分隔符(比如空格、短横线),只需修改join的参数:

# 用短横线分隔列名层级
res.columns = res.columns.map('-'.join)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:02:16