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

如何从嵌套字典创建嵌套结构的Pandas DataFrame?

如何将嵌套字典转换为指定结构的Pandas DataFrame?

我有如下嵌套字典:

nested_dict = {
    'Type A':   {'Type A':  10, 'Type B': 20},
    'Type EE':  {'Type B':  40, 'Type C': 50, 'Type A': 60},
    'Type FFF': {'Type ZZ': 70, 'Type FFF': 80, 'Type A': 90, 'Type AA': 1}
}

能否基于该字典创建如下结构的Pandas DataFrame?

classpredictions
TYPE
---------------------
Type AType A
Type B
---------------------
Type EEType B
Type C
Type A
---------------------
Type FFFType ZZ
Type FFF
Type A
Type AA

可以实现,具体步骤如下:

1. 展开嵌套字典

先把嵌套的键值对拆成扁平的三元组列表,方便Pandas处理:

import pandas as pd

nested_dict = {
    'Type A':   {'Type A':  10, 'Type B': 20},
    'Type EE':  {'Type B':  40, 'Type C': 50, 'Type A': 60},
    'Type FFF': {'Type ZZ': 70, 'Type FFF': 80, 'Type A': 90, 'Type AA': 1}
}

# 展开数据为扁平结构
flat_data = []
for class_name, pred_dict in nested_dict.items():
    for pred_type, count in pred_dict.items():
        flat_data.append({
            'class': class_name,
            'TYPE': pred_type,
            'COUNTER': count
        })

2. 创建DataFrame并设置多层列索引

将扁平数据转换成DataFrame,然后设置符合需求的多层列索引:

df = pd.DataFrame(flat_data)
# 构建多层列索引,对应"predictions"分组下的子列
df.columns = pd.MultiIndex.from_tuples([
    ('class', ''),
    ('predictions', 'TYPE'),
    ('predictions', 'COUNTER')
])

3. 处理行索引实现单元格合并效果

把class列设为行索引,并将重复的class名称替换为空字符串,实现视觉上的单元格合并:

df = df.set_index(('class', ''))
# 替换重复的索引值为空,仅保留每组的第一个class名称
df.index = df.index.set_levels(
    df.index.levels[0].where(~df.index.duplicated(), ''),
    level=0
)

# 查看最终结果
print(df)

运行后输出的DataFrame结构与需求完全一致:

predictions       
                   TYPE COUNTER
class                         
Type A           Type A      10
                 Type B      20
Type EE          Type B      40
                 Type C      50
                 Type A      60
Type FFF         Type ZZ     70
                 Type FFF    80
                 Type A      90
                 Type AA      1

补充说明

如果需要把示例中的Type ZZ改成小写的Type zz,可以在展开数据时对pred_type做处理:pred_type = pred_type.replace('ZZ', 'zz'),或者直接用pred_type = pred_type.lower()统一大小写,根据实际需求调整即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:13:25