Pandas将JSON字符串转换为数据框 - Python

5
我有一个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')

enter image description here

我的期望格式如下

enter image description here

不确定怎么做?


1
如果您尝试使用my_json { "date": ["2017", "2018"] },会发生什么?在引用相同键时,请将值放入数组中。 - Shreamy
3个回答

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

你也可以直接从数据中读取格式,以获取缺失日期:

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

3

我假设my_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_json是字符串格式,您需要调用ast.literal_eval将其转换为字典后再进行处理。

import ast

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

2
您可以直接使用DataFrame,然后对其进行转置,最后再使用reset_index函数。
pd.DataFrame(my_json).T.reset_index().rename(columns={"index":"date"})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接