TransWikia.com

Pandas to Json Formatting issue

Stack Overflow Asked by petereg157 on December 18, 2021

I’ve dataframe something like

**Empty Header | Header 1 | Header 2 | Header 3**
date1-date2  | data 12   | data 12   | data 12
date3-date4  | data 34   | data 34   | data 34
date5-date6  | data 56   | data 56   | data 56
date7-date8  | data 78   | data 78   | data 78

I want to create a json file out of this of format

[
"date1-date2":{
"Header 1": "Data 12",
"Header 2": "Data 12",
"Header 3": "Data 12"
},
.
.
.
"date7-date8":{
"Header 1": "Data 78",
"Header 2": "Data 78",
"Header 3": "Data 78"
}
]

I have used df.to_json(orient='records') but this makes the first column inside the json object.
Any help will be appreciated.

One Answer

You could try this:

df.set_index('Empty Header').to_json(orient='index')

Output:

{'date1-date2': {'Header 1': 'data 12',
  'Header 2': 'data 12',
  'Header 3': 'data 12'},
 'date3-date4': {'Header 1': 'data 34',
  'Header 2': 'data 34',
  'Header 3': 'data 34'},
 'date5-date6': {'Header 1': 'data 56',
  'Header 2': 'data 56',
  'Header 3': 'data 56'},
 'date7-date8': {'Header 1': 'data 78',
  'Header 2': 'data 78',
  'Header 3': 'data 78'}}

Answered by MrNobody33 on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP