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

Unpack nested Dictionary in Column DataFrame Pandas

I have a DataFrame like this

pd.DataFrame([{'ISO3': 'AFG', 'indicator_value': {'137506':{'2012':0.489, '2014':0.49}}}])

enter image description here

While I need a DataFrame in this format:

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

pd.DataFrame([{'indicator_ID':137506, 'ISO3': 'AFG', '2012': 0.489, '2014':0.49}, 
             {'indicator_ID':137506, 'ISO3': 'ALB', '2012': 0.49, '2014':0.5}])

enter image description here

>Solution :

Try this

df = pd.DataFrame([{'ISO3': 'AFG', 'indicator_value': {'137506':{'2012':0.489, '2014':0.49}}}])

# reformat column indicator_value into a list of dictionaries
# and build a df
res = pd.DataFrame([{'indicator_ID': k, **d[k]} for d in df['indicator_value'] for k in d])
# insert ISO3 column
res.insert(1,'ISO3', df.ISO3)
res

enter image description here

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