You need to enable JavaScript to run this app. 如何将含元组列表的多层嵌套字典转换为pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何将含元组列表的多层嵌套字典转换为pandas DataFrame

嵌套字典转目标结构DataFrame的实现

最终生成的表为两级列索引宽表:列第一层级为S1、S2分组,第二层级为分组对应的w1、w2等词项,行索引为a、b、c,单元格存储元组对应的数值,和参考布局完全对齐。

完整可运行代码

import pandas as pd

# 原始嵌套字典
raw_data = {
  'S1': {
    'w1': [('a',0), ('b',1), ('c',3)],
    'w2': [('a',1), ('b',2), ('c',5)], 
    'w3': [('a',1), ('b',1), ('c',4)]
  },
  'S2': {
    'w4': [('a',1), ('b',2), ('c',5)],
    'w5': [('a',0), ('b',3), ('c',4)], 
    'w6': [('a',3), ('b',3), ('c',6)]
  }
}

# 拆解嵌套结构
col_paths = []
row_set = set()
value_map = []

for group_name, group_items in raw_data.items():
    for word_col, item_list in group_items.items():
        col_paths.append( (group_name, word_col) )
        for row_tag, num in item_list:
            row_set.add(row_tag)
            value_map.append( (group_name, word_col, row_tag, num) )

# 初始化空表
result_df = pd.DataFrame(
    index=sorted(row_set),
    columns=pd.MultiIndex.from_tuples(col_paths)
)

# 填充数值
for group_name, word_col, row_tag, num in value_map:
    result_df.loc[row_tag, (group_name, word_col)] = num

输出的表样例

S1                S2
        w1  w2  w3      w4  w5  w6
a       0   1   1       1   0   3
b       1   2   1       2   3   3
c       3   5   4       5   4   6

实操提示

  • pandas 1.1+版本会自动保留原始字典的插入顺序,生成的列顺序和你书写的原始字典顺序完全一致,不会打乱
  • 行索引默认按a、b、c的字典序排列,和参考布局的行顺序匹配
  • 定位多级列时用(一级列名, 二级列名)的元组形式,能避免同名列错位的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 20:54:02