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

合并多级索引DataFrame时合并同层级同名列的方法求助

解决多级索引DataFrame合并后列层级重复的问题

嘿,这个问题我碰到过!当你用pd.concat(axis=1)合并两个拥有相同上层列索引的多级索引DataFrame时,有时候会因为索引对齐的细节,出现重复的上层层级显示,但我们可以轻松把它们合并成单一的层级结构。

先还原你的数据结构,方便后续演示:

import pandas as pd

# 构建df1:两级列索引,上层为'Column',子列col1、col2
df1 = pd.DataFrame(
    [[1, 3], [2, 4]],
    columns=pd.MultiIndex.from_tuples([('Column', 'col1'), ('Column', 'col2')])
)

# 构建df2:同样两级列索引,上层为'Column',子列col3
df2 = pd.DataFrame(
    [[5], [6]],
    columns=pd.MultiIndex.from_tuples([('Column', 'col3')])
)

为什么会出现重复的'Column'层级?

通常这种情况是因为pd.concat()默认保留每个DataFrame的完整列索引结构,如果两个df的子列在索引中不连续(或行索引存在微小差异),显示时会把相同的上层索引拆分开。如果确实出现两个独立的'Column'层级,大概率是两个df的列索引在层级定义上有细微差别(比如层级名称不一致、子列索引类型不同)。

解决方案:两种方法实现单一'Column'层级

方法1:使用df.join()(最直接)

join()专门用于按行索引合并列,会自动合并相同上层列索引的子列,完美适配你的需求:

result = df1.join(df2)

打印结果会得到你想要的结构:

Column
            col1 col2 col3
0            1    3    5
1            2    4    6

方法2:修复pd.concat()的结果

如果你坚持用pd.concat(),可以在合并后通过groupby按列的上层索引聚合,确保子列都归到同一个'Column'下:

# 先执行合并
combined = pd.concat([df1, df2], axis=1)
# 按列的第0层(上层)分组,移除重复的上层索引
result = combined.groupby(level=0, axis=1).apply(lambda x: x.droplevel(0, axis=1))
# 重新设置统一的两级列索引
result.columns = pd.MultiIndex.from_tuples([('Column', col) for col in result.columns])

验证结果

你可以通过以下代码确认列索引结构:

print(result.columns)
# 输出:
# MultiIndex([('Column', 'col1'),
#             ('Column', 'col2'),
#             ('Column', 'col3')],
#            )

这样就完美实现了单一'Column'层级下包含所有子列的DataFrame啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:22:57