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

如何将大洲-国家字典映射到DataFrame的国家列以生成对应大洲列

问题原因

map()返回全为NA的核心原因是你使用的字典结构和pandas.Series.map()的要求不匹配:map()传入字典时,要求字典的键为Series里待匹配的元素(即国家名),值为要映射的结果(即大洲名),你当前的字典结构刚好相反,键是大洲名、值是国家列表,自然无法完成匹配,返回全NA。


两种实现方案

方案1:转换字典结构后直接使用map()(性能更高,推荐)

先把原有字典翻转为「国家名: 大洲名」的结构,再调用map()即可:

# 翻转字典结构
country_continent_map = {}
for continent, countries in continents.items():
    for country in countries:
        country_continent_map[country] = continent

# 映射生成新列
df['Continents'] = df['Country'].map(country_continent_map)

方案2:自定义函数结合map()(灵活性更高,适合复杂匹配规则)

如果后续需要增加特殊匹配逻辑,可以自定义判断函数传入map():

def match_continent(country):
    for continent, countries in continents.items():
        if country in countries:
            return continent
    # 未匹配到的国家返回自定义默认值
    return "Unknown"

df['Continents'] = df['Country'].map(match_continent)

异常排查

如果调整后仍有NA值,检查两点:

  • 国家名字符串是否存在大小写、前后空格不一致的问题,比如DataFrame中是'united states'或'Canada ',和字典中的字符串不匹配
  • 对应国家未收录到你的大洲字典中,可自行补充字典内容或设置默认返回值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:00:04