Reputation: 216
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?
Upvotes: 0
Views: 22
Reputation: 323226
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}}}
Upvotes: 2