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

如何用Python对比pycountry国家列表与Excel中CountryName列的国家?

正确校验Excel中CountryName列与pycountry国家列表的方法

原代码存在的问题

  • 列名校验错误:原代码检查'Sold To Customer Country'列是否存在,但实际使用的是'CountryName'列,逻辑完全不符。
  • 循环变量误用:内层循环用pycountry.name作为变量名,会覆盖pycountry库的属性,导致后续无法正常调用库方法。
  • 比较逻辑错误:原代码拿整个input_countries Series与pycountry对象列表对比,而非单个国家名称与pycountry的国家名称属性对比。
  • 无结果存储:仅做了判断但未保留或输出校验结果,无法查看哪些国家无效。

高效解决方案(推荐)

利用集合的O(1)查找特性,先把pycountry的所有国家名称存入集合,再批量校验Excel中的国家名称,效率远高于双层循环:

import pandas as pd
import pycountry

# 读取Excel数据
df = pd.read_excel(r"V1.xlsx")

# 确保CountryName列存在
if 'CountryName' not in df.columns:
    raise ValueError("Excel文件中不存在'CountryName'列")

# 生成pycountry国家名称的小写集合(兼容大小写不一致的情况)
pycountry_names = {country.name.lower() for country in pycountry.countries}

# 定义校验函数,处理空值和大小写问题
def validate_country(name):
    if pd.isna(name):
        return 'invalid'
    return 'valid' if str(name).lower() in pycountry_names else 'invalid'

# 为DataFrame添加校验结果列
df['CountryValidation'] = df['CountryName'].apply(validate_country)

# 输出校验结果
print(df[['CountryName', 'CountryValidation']])

修正后的双层循环实现

如果一定要用双层循环,需修正变量和比较逻辑:

import pandas as pd
import pycountry

df = pd.read_excel(r"V1.xlsx")

if 'CountryName' not in df.columns:
    raise ValueError("Excel文件中不存在'CountryName'列")

pycountry_countries = list(pycountry.countries)
validation_results = []

for raw_name in df['CountryName']:
    is_valid = False
    # 处理空值情况
    if pd.notna(raw_name):
        target_name = str(raw_name).lower()
        # 遍历pycountry国家列表
        for country in pycountry_countries:
            if country.name.lower() == target_name:
                is_valid = True
                break
    validation_results.append('valid' if is_valid else 'invalid')

# 将结果存入DataFrame
df['CountryValidation'] = validation_results
print(df[['CountryName', 'CountryValidation']])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:58:13