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'?
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']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.