Pandas: give group-key as argument to function in groupby.apply

Viewed 352

I am working with a dataset df_cities containing the following columns:

city_name, country_name, population, language

I have the following function for sorting the table based on if the country is in some list:

special_countries = ['Morocco', 'Turkey', 'Japan' ]

def sort_function(df, country_name):
    if country_name in special_countries:
         return df.sort_values(by='population')
    else:
         return df

Next, I want to use groupby to apply this sorting:

df_cities.groupby('country_name').apply(sort_function, kwargs={'country_name': x})

This ofcourse doesnt work since I have not declared x anywhere. My question is: How can I provide the key of the group (in this case country_name) as an argument to the function I am passing in the .apply()?

0 Answers
Related