How to convert a list of countries into their corresponding continents using pycountry_convert?

819 Views Asked by At

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

1

There are 1 best solutions below

4
On

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 country
  • Bolivia (Plurinational State of): Just called Bolivia by the lib
  • Channel Islands: Not a country
  • China, Hong Kong SAR: Just Hong Kong
  • China, Macao SAR: Just Macao
  • China, mainland: Not sure why there is China as well as this.
  • China, Taiwan Province of: Just Taiwan

I'll stop here since you get the drift. Some dataset cleeanup necessary, after that it works.