'How to use pycountry_convert to create a new column in a DataFrame that lists the continent that the country is in?

I have a DataFrame as follows

df = pd.DataFrame({'Country':['Italy', 'Spain', 'China']})

I wish to create a new column called 'Continent'.

I also know of pycountry_convert, that outputs a continent code. eg this:

country_code = pc.country_name_to_country_alpha2("Germany", cn_name_format="default")
print(country_code)
continent_name = pc.country_alpha2_to_continent_code(country_code)
print(continent_name)

How can I use this code to update the new column of 'Continent'?



Solution 1:[1]

Use lambda function:

f = lambda x: pc.country_name_to_country_alpha2(x, cn_name_format="default")
df['new'] = df['Country'].apply(f)

Or list comprehension:

df['new'] = [pc.country_name_to_country_alpha2(x, cn_name_format="default") 
                                                                    for x in df['Country']]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1