-4
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(df['country'])

[country_to_continent(country)for country in countries] 
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

country_name = list(df['country'])
country_to_continent(country_name)

Acutually I can't get it why my second one is wrong but the first one is right . and get unhashable error

Kevin Su
  • 91
  • 2
  • 8

2 Answers2

1

In the second snippet, you pass list of countries to country_to_continent function, which according to the first example, receives a single country as a parameter.

If you want to convert the whole column in your Dataframe, try instead:

print(df["country"].apply(lambda x: country_to_continent(x)))
Gabio
  • 9,126
  • 3
  • 12
  • 32
0

You're getting unhashable type error in the second one because your function is assuming that the parameter passed to it is a country_name and not a list of country_name.

When you do this [country_to_continent(country)for country in countries], you are passing every element of countries one by one to your function.

However, when you say

country_name = list(df['country'])
country_to_continent(country_name)

You pass the entire list in one go to your function, which results in that error.

Swetank Poddar
  • 1,257
  • 9
  • 23