Following code is given, we need to sum up the medals.

import pandas as pd

# Defining the three dataframes indicating the gold, silver, and bronze medal counts
# of different countries
gold = pd.DataFrame({'Country': ['USA', 'France', 'Russia'],
                         'Medals': [15, 13, 9]}
silver = pd.DataFrame({'Country': ['USA', 'Germany', 'Russia'],
                        'Medals': [29, 20, 16]}
bronze = pd.DataFrame({'Country': ['France', 'USA', 'UK'],
                        'Medals': [40, 28, 27]}

I wrote this working solution. However, it feels very un-pythonic: And I feel there is a better way of approaching this.

df = gold.set_index('Country')["Medals"].add(silver.set_index('Country')["Medals"], fill_value=0).add(bronze.set_index('Country')["Medals"], fill_value=0)
df = pd.DataFrame(df.sort_values(ascending=False))

1 Answer 1


I was provided with this answer by someone:

# Set the index of the dataframes to 'Country' so that you can get the countrywise
# medal count
gold.set_index('Country', inplace = True)
silver.set_index('Country', inplace = True) 
bronze.set_index('Country', inplace = True) 

# Add the three dataframes and set the fill_value argument to zero to avoid getting
# NaN values
total = gold.add(silver, fill_value = 0).add(bronze, fill_value = 0)

# Sort the resultant dataframe in a descending order
total = total.sort_values(by = 'Medals', ascending = False)

# Print the sorted dataframe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.