首页 > 解决方案 > 'NoneType' 对象在使用 pycountry 库时没有属性 'name'

问题描述

我在 DataFrame 中有一个带有国家/地区代码的列,我想将其转换为名称以使用该库绘制图表pycountry

def get_country(n):
    country = countries.get(alpha_2 = n)
    return country.name

我想像这样在DataFrame上使用上面的功能

df['country'] = df['country'].apply(get_country)

我得到这个错误

AttributeError: 'NoneType' object has no attribute 'name'

标签: pythonpandaspycountry-convert

解决方案


get()如果未找到密钥,则默认返回None。你需要检查一下。

def get_country(n):
    country = countries.get(alpha_2 = n)
    if country:
        return country.name
    else:
        return n # keep the original code if no name found

推荐阅读