1

I am a beginner, so feedback is welcome.

I have a dictionary of data frames, with each value of the dictionary a data frame containing data from a specific country. I'd like to create a total data frame, that shows the sum of each of the data frames in the dictionary.

d['total'] = d['Germany'].add(d['Belgium'], fill_value=0)
d['total'] = d['total'].add(d['France'], fill_value=0)

This works perfectly fine for two dataframes, but I have n number of dataframes in my dictionary, so I thought it was stupid to repeat this for each country. Is there a better way to do this?

STerliakov
  • 4,983
  • 3
  • 15
  • 37

1 Answers1

2

To sum all existing DataFrames in the dictionary, you can use:

d['total'] = sum(d.values())

Or to limit to a list of keys:

l = ['Germany', 'Belgium', 'France']

d['total'] = sum(d[c] for c in l)

using only numeric columns:

d['total'] = sum(d[c].select_dtypes('number') for c in l)
mozway
  • 194,879
  • 13
  • 39
  • 75