Home > Net >  How to integrate a list of dictionaries in a dataframe?
How to integrate a list of dictionaries in a dataframe?

Time:04-28

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.

CodePudding user response:

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}]
  • Related