Ariel Ariel -4 years ago 244
JSON Question

Python dataframe to JSON add additional fields

I am looking to transform my dataframe to json

Age Eye Gender
30 blue male

My current code, I convert the dataframe to json and get the below result:

json_file = df.to_json(orient='records')



However, I want to add an additional layer that would state the id and name to the json data and then label it as 'info'.

'info': [

How would I add the additional fields? I tried reading the docs however I do not see a clear answer on how to add the additional fields in during dataframe to json conversion.

Answer Source

Based on the data you provided this is your answer:

import pandas as pd

a = {'id':'5231',

df = pd.DataFrame({'Age':[30], 'Eye':['blue'], 'Gender': ['male']})
json = df.to_json(orient='records')

a['info'] = json
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download