将JSON字符串转换为Dataframe Python

2024-04-26 04:48:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

不知道怎么做?你知道吗


Tags: 数据字符串代码fromjsondataframeclosemy
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.iteral_eval将其转换为字典

import ast

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

您可以直接使用DataFrame,然后转置它,然后reset_index

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

相关问题 更多 >