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

如何拆分嵌套字典以映射至DataFrame索引

拆分嵌套字典为独立字典的方法

你可以通过字典推导式快速将嵌套字典拆分为所需的high_dict和low_dict,这是最直观高效的方式:

# 提取嵌套字典中的high字段构建新字典
high_dict = {key: sub_dict['high'] for key, sub_dict in nested_dict.items()}

# 提取嵌套字典中的low字段构建新字典
low_dict = {key: sub_dict['low'] for key, sub_dict in nested_dict.items()}

原理说明

遍历原嵌套字典的每一组键值对:

  • key是外层字典的键(如4.0、7.0)
  • sub_dict是对应内层的子字典(如{'high': 93.34, 'low': 91.53})
  • 直接提取子字典中high或low的值,与外层键配对生成目标字典

额外优化:无需拆分直接关联DataFrame

其实你可以跳过拆分字典的步骤,直接将嵌套字典转为DataFrame后与原表关联,代码更简洁:

import pandas as pd

# 将嵌套字典转为DataFrame,外层键作为索引
nested_df = pd.DataFrame.from_dict(nested_dict, orient='index')
# 与原DataFrame按索引合并
df = df.join(nested_df)

内容的提问来源于stack exchange,提问作者DISC-O

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:10:27