Skip to main content
 首页 » 编程设计

python之如何将 JSON 文件读入 Dataframe

2025年05月04日27JeffreyZhao

我是 python 的新手,所以有人可以帮助我吗?

我在 json 文件中有以下内容(即 file12.json)

{ 
    "TimeSeries": { 
        "Row": [ 
            { 
                "CLOSE": 41.85, 
                "TIMESTAMP": "2016-09-22T00:00:00+00:00" 
            }, 
            { 
                "CLOSE": 41.37, 
                "TIMESTAMP": "2016-09-23T00:00:00+00:00" 
            }, 
            { 
                "CLOSE": 40.88, 
                "TIMESTAMP": "2016-09-26T00:00:00+00:00" 
            }, 
            { 
                "CLOSE": 40.98, 
                "TIMESTAMP": "2016-09-27T00:00:00+00:00" 
            }, 
            { 
                "CLOSE": 44.33, 
                "TIMESTAMP": "2016-12-21T00:00:00+00:00" 
            } 
        ] 
    } 
} 

我正在尝试创建一个结构化的 Dataframe,如下所示:

      CLOSE        TIMESTAMP 
0     41.85        2016-09-22T00:00:00+00:00  
1     41.37        2016-09-23T00:00:00+00:00  
2     40.88        2016-09-26T00:00:00+00:00 
3     40.98        2016-09-27T00:00:00+00:00  

如果我想对 csv 执行相同的操作,我只需使用“read_csv”,但 read_python 会产生不同的输出。

我用过这个代码...

file = pd.read_json('file12.json') 
print file 

...但格式并不完全符合我的要求。我得到以下信息:

TimeSeries 
Row  [{u'CLOSE': 41.85, u'TIMESTAMP': u'2016-09-22T... 

..即。一切都简单地在一行中,而不是在格式化的表格中。

谁能帮帮我?请 : - )

请您参考如下方法:

在 McKinney 的 Python for Data Analysis 中,他说

How you convert a JSON object or list of objects to a DataFrame or some other data structure for analysis will be up to you.

试试这个(这个未经测试的代码,ymmv)

import json 
import pandas as pd 
with open('file12.json') as json_data: 
   obj = json.load(json_data) 
   frame = pd.DataFrame(obj['TimeSeries']['Row'], columns=['CLOSE', 'TIMESTAMP'])