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 integrate a list of dictionaries in a dataframe?

I have a pandas dataframe

ID  Name Score Score_scale
1   ABC   1      5
2   DEF   2      5
3   GHI   3      5

I need to convert it to the following format

ID  Name  Score
1   ABC   [{'score_scale':5, 'score':1}]
2   DEF   [{'score_scale':5, 'score':2}]
3   GHI   [{'score_scale':5, 'score':3}]

Need your help. Thank you.

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 :

First idea is use DataFrame.to_dict, but nested lists are not created:

df['Score'] = df[['Score','Score_scale']].to_dict('records')
df = df.drop('Score_scale', 1)
print (df)
   ID Name                           Score
0   1  ABC  {'Score': 1, 'Score_scale': 5}
1   2  DEF  {'Score': 2, 'Score_scale': 5}
2   3  GHI  {'Score': 3, 'Score_scale': 5}

If need nested values:

df['Score'] = [[x] for x in df[['Score','Score_scale']].to_dict('records')]
df = df.drop('Score_scale', 1)
print (df)
   ID Name                             Score
0   1  ABC  [{'Score': 1, 'Score_scale': 5}]
1   2  DEF  [{'Score': 2, 'Score_scale': 5}]
2   3  GHI  [{'Score': 3, 'Score_scale': 5}]
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