Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge pandas column of dictionaries into one dict

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading