Home > database >  How to change dataframe into a specific json format?
How to change dataframe into a specific json format?

Time:04-05

I want to convert the below dataframe into the json formation as mentioned:

Dataframe:

enter image description here

Desired Ouput:

{"Adam": [{"name": "ABC", "y": 2.0}, {"name": "DEF", "y": 5}], 
"John": [{"name": "GHI", "y": 29.01}, {"name": "FMI", "y": 219.77}]}

I tried creating the index of Party column and use df.to_json(orient="index") but its failing due to duplicate in index columns (Party column). Can someone please help.

CodePudding user response:

Use custom lambda function in GroupBy.apply:

j = (df.groupby('Party')[['name','y']]
       .apply(lambda x: x.to_dict('records'))
       .to_json(orient="index"))
print (j)

{"Adam":[{"name":"ABC","y":2.0},{"name":"DEF","y":5.0}],
 "John":[{"name":"GHI","y":29.01},{"name":"FMI","y":219.77}]}
  • Related