I am trying to convert the list of countries in my dataset into their corresponding continents . I am using this code for help link: country convert to continent
but i got error when try to execute the code given above :
" KeyError: "Invalid Country Alpha-2 code: 'AQ'" "
Here is my code :
import pycountry_convert as pc
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
countries = list(temp['Area'])
[country_to_continent(country)for country in countries]
temp is the name of my dataset
The error indicated is caused by the translation from country name to alpha2 code. In the lib source files AQ (the offical code) is missing (under windows in
AppData\Local\Programs\Python\Python310\Lib\site-packages\pycountry_convert\convert_country_alpha2_to_continent_code.py
I added'AQ': 'AN',
on line 19).However, there some error after that cause by the naming of some countries (the dataset does not claim those are countries but rather areas):
Belgium-Luxembourg
: not a countryBolivia (Plurinational State of)
: Just calledBolivia
by the libChannel Islands
: Not a countryChina, Hong Kong SAR
: JustHong Kong
China, Macao SAR
: JustMacao
China, mainland
: Not sure why there isChina
as well as this.China, Taiwan Province of
: JustTaiwan
I'll stop here since you get the drift. Some dataset cleeanup necessary, after that it works.