I have a column of dictionaries within a pandas data frame:
sr = pd.Series([{'sugar': 1, 'pepper': 2},{'salt': 2, 'sugar': 2},{'pepper': 3, 'sugar': 4}])
df = pd.DataFrame({'column1': sr})
df
column1
0 {'sugar': 1, 'pepper': 2}
1 {'salt': 2, 'sugar': 2}
2 {'pepper': 3, 'sugar': 4}
How would I merge all dictionaries in column ‘column1’ into one dictionary, where the values are the sum of the respective values in their dictionaries?
This question is very similar to this one:link
However, I don’t get the Counter method to take the sum.
Expected output:
{'sugar': 7, 'pepper': 5, 'salt': 2}
I tried some lambda function to iterate over all rows, and also to explode each key to columns and then take the sum. This however does not work, since the actual df is quite large.
>Solution :
With pd.DataFrame.from_records:
pd.DataFrame.from_records(df['column1']).sum().to_dict()
{'sugar': 7.0, 'pepper': 5.0, 'salt': 2.0}