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

Create nested dictionary from mulitple dataframe columns and Groupby

Original Dataframe example:

ColA     ColB     ColC
Dog      Red       8
Dog      Black     10
Dog      White     2
Dog      Blue      4
Cat      Red       7
Cat      Black     11
Cat      White     12
Cat      Blue      40

Desired dictionary

d =   {'Dog':{'Red': 8, 'Black':10, 'White':2,'Blue':4}, 
       'Cat':{'Red': 7, 'Black':11, 'White':12,'Blue':40}}

Any suggestions is appreciated!

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

>Solution :

There might be more panda-esque ways, but this works:

result = {animal:dict(zip(subdf.ColB, subdf.ColC)) for animal, subdf in df.groupby('ColA')}
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