python - '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'
解决方案
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
推荐阅读
- c# - 基于 BouncyCastle 的 PrivateBin API 实现
- android - Android Studio 3.6 测试框架意外退出,编排器崩溃
- python - 根据特定键统一字典列表 - 在重复的情况下保留特定的出现
- asp.net-core - 是否可以更改 UserManager
的一生? - ios - UIView 内的 CollectionView 重复
- gcc - 当前缀为 /usr/local 时,libepoxy 的 autogen 找不到 xorg-macros
- amazon-web-services - MOTO后端服务如何创建bucket
- python - 如何使用 sklearn 对不平衡数据集的逻辑回归进行评估?
- python - 修复我的 Python 安装和 Jupyter Notebook
- scala - Scala:如何访问在其他代码块中定义的方法中的变量