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

如何将Python三级嵌套字典转换为Pandas多层表头表格?

三级嵌套字典转Pandas多层表头表格解决方案

问题描述

现有三级嵌套字典数据,直接用pd.DataFrame(data)生成的表格不符合需求,需要构建如下结构的多层表头表格:

---------------------------------------
|       |  text1        |    text2    |
|       |------------------------------
| Block | key1  | key2 | key1 | key2 |
---------------------------------------
| block1|value1 |value2 |value3|value4|
---------------------------------------
| block2|value5 |value6 |value7|value8|
---------------------------------------

实现代码

import pandas as pd

data = {
    "block1": {
        "text1": {
            "key1": "value1",
            "key2": "value2",
        },
        "text2": {
            "key1": "value3",
            "key2": "value4",
        },
    },
    "block2": {
        "text1": {
            "key1": "value5",
            "key2": "value6",
        },
        "text2": {
            "key1": "value7",
            "key2": "value8",
        },
    },
}

# 转换数据结构,生成带多层索引的DataFrame
df = pd.concat({block: pd.DataFrame(texts).T for block, texts in data.items()})

# 重置索引并调整列层级
df = df.reset_index().rename(columns={'level_0': 'Block'})
df.columns = pd.MultiIndex.from_tuples(
    [('Block', ''), ('text1', 'key1'), ('text1', 'key2'), ('text2', 'key1'), ('text2', 'key2')]
)

# 打印符合样式的表格
print(df.to_string(index=False))

代码说明

  1. 数据结构转换:通过字典推导式遍历外层block,将每个block内的text字典转为DataFrame并转置,再用pd.concat合并,让block成为临时索引。
  2. 索引与列层级调整:重置索引提取block为单独列,然后手动构建多层列索引,对应需求中的表头层级(上层为text1/text2,下层为key1/key2,第一列上层为空、下层为Block)。
  3. 表格输出:用to_string(index=False)去掉默认索引,打印出符合要求的表格样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:23:33