1

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')

json_file

[{'age':'30'},{'eye':'blue'},{'gender':'male'}]

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'.

{'id':'5231'
 'name':'Bob'
 'info': [
          {'age':'30'},{'eye':'blue'},{'gender':'male'}
         ]
 }

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.

Ariel
  • 928
  • 4
  • 15
  • 32

1 Answers1

1

Based on the data you provided this is your answer:

import pandas as pd

a = {'id':'5231',
    'name':'Bob',
}

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

a['info'] = json
zipa
  • 27,316
  • 6
  • 40
  • 58