Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JSON字符串转换为Dataframe-Python_Python_Json_Pandas - Fatal编程技术网

将JSON字符串转换为Dataframe-Python

将JSON字符串转换为Dataframe-Python,python,json,pandas,Python,Json,Pandas,我有一个json字符串,需要转换为具有所需列名的数据帧 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}

我有一个json字符串,需要转换为具有所需列名的数据帧

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}}
使用下面的代码没有给出我想要的格式

pd.DataFrame.from_dict(json_normalize(my_json), orient='columns')

我期望的格式如下


不知道怎么做?

您可以直接使用
数据帧
,然后转置它,然后
重置索引

pd.DataFrame(my_json).T.reset_index().rename(columns={"index":"date"})

您也可以通过这种方式获得确切的格式:

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
您也可以直接从数据中读取,以获取缺少日期的格式:

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

我假设我的json是字典。也就是说,它不是字符串格式

pd.DataFrame.from_dict(my_json, orient='index').rename_axis('date').reset_index()

Out[632]:
         date    open    high     low   close   volume
0  2017-01-03  214.86  220.33  210.96  216.99  5923254
1  2017-12-29  316.18  316.41  310.00  311.35  3777155

如果
my\u json
为字符串格式,则需要调用
ast.iteral\u eval
将其转换为字典,然后再进行处理

import ast

d = ast.literal_eval(my_json)
pd.DataFrame.from_dict(d, orient='index').rename_axis('date').reset_index()

如果您尝试我的{“日期”:[“2017”,“2018”]},会发生什么?当引用同一个键时,将值作为数组。