如何基于指定条件将Pandas DataFrame转换为目标嵌套字典结构
核心问题定位
- 字典键类型错误:Python中可变类型(比如列表)不能作为字典的key,你预期结构里的
["Spot month Lim", "Aggregate Lim"]是列表,无法直接当键,必须换成不可变的(Spot month Lim, Aggregate Lim)元组类型。 - 字典结构初始化不匹配:你最开始初始化
ifeu_dict[principal] = []给的是列表,后面又想把它当字典用ifeu_dict[principal][limit_tuple],类型不匹配必然报错。
修复后代码
首先调整初始化逻辑,用嵌套的defaultdict结构匹配你的目标层级,同时简化重复的类型转换逻辑:
from collections import defaultdict # 初始化嵌套结构:外层key是Principal Venue Product Code,对应值为字典;内层key是limit元组,对应值是存Venue Product Codes的列表 ifeu_dict = defaultdict(lambda: defaultdict(list)) for idx, row in df.iterrows(): if row.loc["Venue MIC"] != "IFEU": continue # 统一提取字段,避免重复取值 spot_lim = row.loc["Spot month single limit#"] other_lim = row.loc["Other month limit#"] product_code = row.loc["Venue Product Codes"] principal = row.loc["Principal Venue Product Code"] # 统一处理limit值转整数的逻辑,兼容字符串、数字两种输入 try: if isinstance(spot_lim, str): spot_lim = int(spot_lim.split()[0].replace(",", "")) other_lim = int(str(other_lim).split()[0].replace(",", "")) # 确保最终limit是int类型 spot_lim = int(spot_lim) other_lim = int(other_lim) except (ValueError, TypeError): # 转换失败直接跳过当前行 continue # 以limit元组为key,追加对应的product code limit_key = (spot_lim, other_lim) ifeu_dict[principal][limit_key].append(product_code)
如果你确实需要将key转为列表格式(仅可用于输出展示,无法用作字典索引),可以后续再做一次格式转换:
output_dict = { principal: { list(limit_key): product_list for limit_key, product_list in principal_data.items() } for principal, principal_data in ifeu_dict.items() }
额外说明
- 你原代码中
for (col, row) in df.iterrows()属于笔误,iterrows返回的是(行索引, 行数据),已经修正为idx, row - 用
isinstance()判断类型比直接type() ==更严谨,能够兼容子类场景
内容的提问来源于stack exchange,提问作者Bamir
相关产品推荐
相关产品推荐

