首页 > 解决方案 > 如何将一个国家/地区的名称转换为具有当前和过时国家/地区单独列表的大陆

问题描述

如何在国家列表中将国家名称转换为大陆名称,其中一些当前存在而另一些不再存在(例如苏联)?

我有一张来自世界各国过去五十年的数据表。我想添加一个模仿所列国家列的新列,然后将国家名称转换为其对应的大陆。

我已经使用了一个函数,pycountry_convert但它只能输入当前存在的国家。有一个 pycountry 工具可以处理不再存在的国家的“历史”名称(例如:苏联),但该列表不包括存在的国家。我认为我的country_to_continent()功能需要能够针对列表、活跃或不活跃的国家/地区测试输入,但我不确定那会是什么样子。

# country_to_continent takes country_name, converts it to an alpha code and then
# looks up the continent using the alpha code.
def country_to_continent(country_name):
    country_alpha2 = pc.country_name_to_country_alpha2(country_name)
    country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2)
    country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code)
    return country_continent_name

#create new column
hivdata.insert(1,"column1", np.nan)
#new column replicates first column indexing by country name
hivdata["column1"] = hivdata['Estimated HIV Prevalence% - (Ages 15-49)']
#apply function to column 1
hivdata['column1'] = hivdata['column1'].apply(country_to_continent)

错误:

     70     if cn_name not in dict_country_name_to_country_alpha2:
---> 71         raise KeyError("Invalid Country Name: '{0}'".format(cn_name))
     72
     73     return dict_country_name_to_country_alpha2[cn_name]

KeyError: "Invalid Country Name: 'Abkhazia'"

标签: pythonexcelpycountry-convert

解决方案


推荐阅读