You need to enable JavaScript to run this app. 如何用嵌套字典创建仅包含1列的pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何用嵌套字典创建仅包含1列的pandas DataFrame

嵌套字典转单列Pandas DataFrame实现

问题描述

需要将结构为「外层键为数字,值为数值集合」的嵌套字典转换为单列存储容器数据的DataFrame,现有参考实现代码如下:

import pandas as pd
my_dict = {
    0: {1,5,8},
    1: {2,7,6},
    2: {8,3,7}
}
df = pd.DataFrame.from_dict(my_dict, orient='index', dtype=None, columns=None)
print(df)

现有实现的输出

代码运行后pandas会自动拆解集合元素,生成多列结构:

0  1  2
0  8  1  5
1  2  6  7
2  8  3  7

期望输出

需要将所有集合内容完整存储在单个列的单元格中,不做拆分:

number column
0       0  1,5,8
1       1  2,6,7
2       2  8,3,7

核心约束:不需要生成多列,每个单元格需存储列表、集合这类可迭代容器,或等价的拼接字符串值。

正确实现方法

原理说明:pd.DataFrame.from_dict 默认会拆解可迭代对象的元素生成多列,只要把每个集合值额外嵌套一层列表作为单个单元格的入参,就可以阻断这个自动拆解逻辑。
实现步骤:

  • 遍历原字典的键值对,将每个集合值作为单个元素封装到列结构中
  • 指定单列的列名
  • 将原字典的外层键重置为独立的number列

代码示例(单元格存储列表类型)

import pandas as pd
my_dict = {
    0: {1,5,8},
    1: {2,7,6},
    2: {8,3,7}
}

# 封装为单列数据结构
col_content = {
    outer_key: [list(inner_set)]
    for outer_key, inner_set in my_dict.items()
}

# 生成DataFrame
df = pd.DataFrame.from_dict(
    col_content,
    orient='index',
    columns=['column']
).reset_index(names='number')

print(df)

运行输出:

number    column
0       0  [1, 5, 8]
1       1  [2, 6, 7]
2       2  [8, 3, 7]

代码示例(单元格存储逗号拼接字符串,匹配展示格式)

import pandas as pd
my_dict = {
    0: {1,5,8},
    1: {2,7,6},
    2: {8,3,7}
}

# 把集合排序后拼接为逗号分隔的字符串
col_content = {
    outer_key: [','.join(map(str, sorted(inner_set)))]
    for outer_key, inner_set in my_dict.items()
}

df = pd.DataFrame.from_dict(
    col_content,
    orient='index',
    columns=['column']
).reset_index(names='number')

print(df)

运行输出与期望完全一致:

number column
0       0  1,5,8
1       1  2,6,7
2       2  8,3,7

内容的提问来源于stack exchange,提问作者Igor K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 07:45:09