0

My Pandas df is like:

RollCall    Physics Chemisty    Maths
1   20  30  25
2   25  30  30
3   15  12  35
4   20  15  30

I wish to convert this to a json like:

{"StudentDetails": {
"1":{"Physics":20,"Chemisty":30,"Maths":25},
"2":{"Physics":25,"Chemisty":30,"Maths":30},
"3":{"Physics":15,"Chemisty":12,"Maths":35},
}}

This is what I am doing and not getting the desired output:

d = {}
d['StudentDetails'] = df.to_json(orient='index')

Anyway to get desired output?

1 Answer 1

2

In your case do

df['RollCall'] = df['RollCall'].astype(str)

d = {}
d['StudentDetails'] = df.set_index('RollCall').to_dict('index')
d
Out[366]: 
{'StudentDetails': {'1': {'Physics': 20, 'Chemisty': 30, 'Maths': 25},
  '2': {'Physics': 25, 'Chemisty': 30, 'Maths': 30},
  '3': {'Physics': 15, 'Chemisty': 12, 'Maths': 35},
  '4': {'Physics': 20, 'Chemisty': 15, 'Maths': 30}}}
Sign up to request clarification or add additional context in comments.

1 Comment

@Anant check the update

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.