0

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.

1 Answer 1

2

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}]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.