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

如何利用字典基于DataFrame的国家名称列填充区域名称列空值

解决方案

1. 重构字典映射逻辑

你原来的字典是区域名对应国家列表,但我们需要的是国家名对应区域名的反向映射,才能通过Country Name直接匹配到对应的区域。另外别用dict当变量名,会覆盖Python内置的字典类型,容易出问题。

# 重命名字典,避免冲突
region_countries_map = {
    "Central and Eastern Europe": [
        "Albania", "Bosnia and Herzegovina", "Bulgaria", "Croatia",
        "Czech Republic", "Estonia", "Hungary", "Kosovo", "Latvia",
        "Lithuania", "Montenegro", "North Macedonia", "Poland",
        "Romania", "Serbia", "Slovakia", "Slovenia"
    ],
    "East Asia": [
        "China", "Hong Kong S.A.R. of China", "Japan", "Mongolia",
        "South Korea", "Taiwan Province of China"
    ],
    # 补充其他区域数据...
}

# 生成反向映射:国家名 → 区域名
country_region_map = {}
for region, countries in region_countries_map.items():
    for country in countries:
        country_region_map[country] = region

2. 正确填充空值

你之前的代码有两个核心错误:

  • 列名不匹配:你的DataFrame列是Country Name和Region Name,但代码里写的是Country name和Regional indicator
  • 映射逻辑搞反了:应该用Country Name匹配区域,而不是反过来

正确的填充代码如下:

# 筛选出Region Name为空的行,用Country Name匹配反向字典填充
df.loc[df['Region Name'].isnull(), 'Region Name'] = df['Country Name'].map(country_region_map)

额外处理建议

  • 如果有部分国家不在你的字典里,map后会返回NaN,可以补充这些国家的区域数据,或者统一填充默认值:
    # 用"Other Region"填充未匹配到的国家
    df['Region Name'] = df['Region Name'].fillna(df['Country Name'].map(country_region_map).fillna("Other Region"))
    
  • 确保Country Name里的国家名称和字典里的完全一致(大小写、空格、特殊字符都不能错),否则会匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:00:25