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

Pandas每行含多个国家时转换为对应大洲的报错解决方法

报错根因

原代码直接将每行包含多个逗号分隔国家的整串文本作为单个国家名传入转换函数,转换库无法识别这类拼接的多国家字符串,必然触发匹配错误。

修复方案

不需要先转ISO3编码再调用pycountry_convert绕路,country_converter本身就内置了大洲映射能力,还能自动识别England这类常见地区别名,容错性更高。核心处理逻辑是:先拆分每行的多国家字符串为单个国家列表,逐国完成转换后,再将结果拼接为和原列格式一致的字符串即可。

可直接运行的修复代码如下:

!pip install country_converter --upgrade
import pandas as pd
import country_converter as coco

cc = coco.CountryConverter()
df = pd.DataFrame()
df['country']=['United States, Canada, England', 'United Kingdom, Spain, South Korea', 'Spain', 'France, Sweden']

def multi_country_to_continent(country_col_str):
    # 按逗号拆分国家,自动去除每个国家名前后的空格
    country_ls = [name.strip() for name in country_col_str.split(',')]
    # 批量转换为大洲,匹配失败的项统一标记为other
    continent_ls = cc.convert(names=country_ls, to='continent', not_found='other')
    # 拼接为逗号分隔的字符串返回
    return ', '.join(continent_ls)

df['Continent'] = df['country'].apply(multi_country_to_continent)
转换结果

运行后得到的DataFrame内容如下:

  • 原country列值United States, Canada, England 对应Continent值 North America, North America, Europe
  • 原country列值United Kingdom, Spain, South Korea 对应Continent值 Europe, Europe, Asia
  • 原country列值Spain 对应Continent值 Europe
  • 原country列值France, Sweden 对应Continent值 Europe, Europe
补充说明
  • 原代码存在拼写错误:自定义字段名写为Contenent属于拼写失误,正确拼写为Continent,修复代码已同步修正
  • 如果需要对同一行内重复的大洲去重(比如多个欧洲国家仅保留一个Europe标记),可以在拼接前加入顺序去重逻辑:continent_ls = list(dict.fromkeys(continent_ls)),该方法不会打乱大洲原本的出现顺序
  • 转换逻辑自动处理了逗号后自带的空格问题,不会因为格式细节导致国家名匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:15:30