Pandas convert JSON string to Dataframe - Python

PyB*_*oss 5 python json pandas

i have a json string that need to be convert to a dataframe with desired column name.

my_json = {'2017-01-03': {'open': 214.86,
  'high': 220.33,
  'low': 210.96,
  'close': 216.99,
  'volume': 5923254},
'2017-12-29': {'open': 316.18,
  'high': 316.41,
  'low': 310.0,
  'close': 311.35,
  'volume': 3777155}}
Run Code Online (Sandbox Code Playgroud)

use below code doesn't give the format i want

pd.DataFrame.from_dict(json_normalize(my_json), orient='columns')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

my expected format is below

在此输入图像描述

Not sure how to do it?

opp*_*yer 4

您还可以通过以下方式获得确切的格式:

pd.DataFrame(my_json).T.rename_axis(columns='Date')                                                                                                                                  

Date          open    high     low   close     volume
2017-01-03  214.86  220.33  210.96  216.99  5923254.0
2017-12-29  316.18  316.41  310.00  311.35  3777155.0
Run Code Online (Sandbox Code Playgroud)

您还可以直接从数据中读取以获取缺少日期的格式:

pd.DataFrame.from_dict(my_json, orient='index').rename_axis(columns='Date')                                                                                                          

Date          open    high     low   close   volume
2017-01-03  214.86  220.33  210.96  216.99  5923254
2017-12-29  316.18  316.41  310.00  311.35  3777155
Run Code Online (Sandbox Code Playgroud)