如何拆分嵌套字典以映射至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
相关产品推荐
相关产品推荐

