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

Python中如何将多个DataFrame插入到三级索引DataFrame中?

实现多二级索引DataFrame合并为三级索引DataFrame

问题描述

我有两个二级索引的DataFrame,代码如下:

import pandas as pd

df1 = pd.DataFrame()
df1["Index1"] = ["A", "AA"]
df1["Index2"] = ["B", "BB"]
df1 = df1.set_index(["Index1", "Index2"])
df1["Value1"] = 1
df1["Value2"] = 2

df2 = pd.DataFrame()
df2["Index1"] = ["X", "XX"]
df2["Index2"] = ["Y", "YY"]
df2["Value1"] = 3
df2["Value2"] = 4
df2 = df2.set_index(["Index1", "Index2"])

我希望将它们合并成一个三级索引的DataFrame,其中第一级索引用来标识数据来自哪个原始DataFrame,预期效果为第一级索引包含"DF1"、"DF2",下方对应各自的二级索引与数据。

理想的实现方式是能通过类似以下的代码批量添加数据:

# 初始化空DataFrame
res = pd.DataFrame(index = pd.MultiIndex(levels = [[], [], []],
                                        codes = [[],[],[]],
                                        names = ["Df number", "Index1", "Index2"]),
                  columns = ["Value1", "Value2"])

res = AddDataFrameAtIndex(index = "DF1", level = 0, dfToInsert = df1)
res = AddDataFrameAtIndex(index = "DF2", level = 0, dfToInsert = df2)

解决方案

方法一:使用pd.concat自动化合并(推荐)

这是最简洁高效的自动化方式,无需手动初始化空DataFrame,只需将多个DataFrame存入字典,通过concat的keys参数自动生成第一级索引:

import pandas as pd

# 用字典存储DataFrame,键即为第一级索引的名称
df_dict = {"DF1": df1, "DF2": df2}

# 合并生成三级索引DataFrame
res = pd.concat(df_dict, names=["Df number", "Index1", "Index2"])

方法二:实现自定义AddDataFrameAtIndex函数

如果要按照你理想的调用方式实现,可编写如下自定义函数:

def AddDataFrameAtIndex(res, index_label, level, dfToInsert):
    # 为待插入的DataFrame添加指定层级的索引
    df_with_level = dfToInsert.reindex(
        pd.MultiIndex.from_product(
            [[index_label]] + list(dfToInsert.index.levels),
            names=[res.index.names[level]] + list(dfToInsert.index.names)
        )
    )
    # 合并到结果DataFrame
    res = pd.concat([res, df_with_level])
    return res

# 初始化空的三级索引DataFrame
res = pd.DataFrame(
    index=pd.MultiIndex(levels=[[], [], []],
                        codes=[[], [], []],
                        names=["Df number", "Index1", "Index2"]),
    columns=["Value1", "Value2"]
)

# 调用函数添加数据
res = AddDataFrameAtIndex(res, "DF1", 0, df1)
res = AddDataFrameAtIndex(res, "DF2", 0, df2)

补充说明

  • 方法一利用pd.concat的原生功能,代码简洁且性能更优,适合批量处理多个结构一致的DataFrame。
  • 方法二实现了自定义的动态添加逻辑,灵活性更强,适合需要逐步添加数据的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:23