Python字典追加值:遍历clients_grouped仅存最后客户数据如何调整
代码问题修复方案
问题原因
你当前代码仅返回最后一位客户的正确结果,核心由三个错误导致:
- 临时计数变量
bands_sum、索引i、档位差值列表bands_differences均在客户遍历循环外初始化,上一个客户计算后修改的数值会直接带入下一个客户的计算逻辑 - 三个存储结果的字典直接用档位名作为主键,不同客户同一档位的计算值会直接覆盖旧值
- 计算过程中直接修改了
bands_differences的原始元素值,后续客户计算时使用的是被前序客户篡改的错误档位差值
修改后代码
import pandas as pd # 固定全局配置参数,不随客户计算修改 bands_factors = [2, 3, 4, 5, 6, 9] default_bands_differences = [40, 20, 20, 20, 150] bands = ("Up to 40%", "40 to 60%", "60 to 80%", "80 to 100%", "100 to 250%", "over than 250%") # 结果字典调整为嵌套结构:{客户索引/ID: {档位名: 计算值}} eve_across_tranches_users = {} OFRE_prorated_users = {} KCON_own_funds_requirement_users = {} for index, row in clients_grouped.iterrows(): # 每次处理新客户时,重置所有临时变量为初始状态 bands_sum = 0 i = 0 bands_differences = default_bands_differences.copy() added_band = False # 为每个客户初始化子字典存储档位结果 eve_across_tranches_users[index] = {} OFRE_prorated_users[index] = {} KCON_own_funds_requirement_users[index] = {} if row["EVE_as_percent"] > 250: bands_differences.append(row["EVE_as_percent"] - sum(bands_differences)) added_band = True while bands_sum < row["EVE_as_percent"] and i < len(bands_differences): check_sum = bands_sum bands_sum += bands_differences[i] # 注意:如果client_limit是每个客户单独的参数,替换为row中对应的字段即可,比如row['client_limit'] if bands_sum > row["EVE_as_percent"]: current_diff = row["EVE_as_percent"] - check_sum eve_across_tranches_users[index][bands[i]] = current_diff / 100 * client_limit OFRE_prorated_users[index][bands[i]] = eve_across_tranches_users[index][bands[i]] / row["EVE"] * row["OFRE"] KCON_own_funds_requirement_users[index][bands[i]] = OFRE_prorated_users[index][bands[i]] * bands_factors[i] break else: eve_across_tranches_users[index][bands[i]] = bands_differences[i] / 100 * client_limit OFRE_prorated_users[index][bands[i]] = eve_across_tranches_users[index][bands[i]] / row["EVE"] * row["OFRE"] KCON_own_funds_requirement_users[index][bands[i]] = OFRE_prorated_users[index][bands[i]] * bands_factors[i] i += 1 # 清理临时追加的档位差值,避免影响后续客户计算 if added_band: bands_differences.pop()
关键修改说明
- 调整结果字典为两层嵌套结构,第一级键为客户索引(可根据需要替换为
row['客户ID']等业务唯一标识),每个客户的档位计算结果独立存储,不会互相覆盖 - 所有临时计算变量的初始化移到客户遍历循环内部,每次处理新客户都重置为初始状态,不受前序客户计算影响
- 原始档位差值设为固定全局变量,每次计算都用副本操作,不会修改原始配置
- 补充了索引越界判断,避免档位数量不匹配时程序报错
内容的提问来源于stack exchange,提问作者Lukasz
相关产品推荐
相关产品推荐

