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

如何在嵌套Python字典中匹配Pandas DataFrame值并更新DataFrame

代码运行错误的核心原因

你写的find_global_name函数中,else分支的return "n/a"放在了for循环内部,第一次遍历字典的key='0'条目时,如果当前行的co-name不等于A,会直接返回n/a,根本不会执行后续的循环迭代去匹配key='1'的B条目,所以除了A之外的所有企业都会被判定为匹配失败。

正确实现方案

推荐优先使用字典重构+map的方案,比apply+循环的性能高很多,尤其适合数据量较大的场景:

步骤1:将嵌套字典重构为co_name为键的查找字典

# 直接用企业名称作为键,后续查找时间复杂度为O(1)
lookup_dict = {val['co_name']: val for val in co_dict.values()}

步骤2:批量匹配生成两个新列

df['global_name'] = df['co-name'].map(lambda x: lookup_dict[x]['global_name'] if x in lookup_dict else 'n/a')
df['sales'] = df['co-name'].map(lambda x: lookup_dict[x]['sales'] if x in lookup_dict else 'n/a')

注:你给出的预期输出中B的sales为2000属于笔误,实际运行会按co_dict中存储的1000返回。

如果你需要保留原来的循环写法,只需要调整return "n/a"的位置到for循环外部即可:

def find_global_name(x):
    for key1 in co_dict.keys():
        if (x['co-name'] == co_dict[key1]['co_name']):
            return co_dict[key1]['global_name']
    # 所有字典条目遍历完成仍未匹配到,再返回n/a
    return "n/a"

def find_sales(x):
    for key1 in co_dict.keys():
        if (x['co-name'] == co_dict[key1]['co_name']):
            return co_dict[key1]['sales']
    return "n/a"
        
df['global_name'] = df.apply(find_global_name, axis=1)
df['sales'] = df.apply(find_sales, axis=1)

这种写法功能可以实现,但数据量较大时运行效率远低于第一种方案,不推荐使用。

内容的提问来源于stack exchange,提问作者vcodingadventures

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:09:01