繁体   English   中英

python:用熊猫读json

[英]python: read json with pandas

我想获取以下json链接的时间戳,高,低,打开,关闭,但我只收到错误c harterror Noneresult [{u'indicators': {u'quote': [{u'high': [45.25,...

我的代码如下:

df = pd.read_json('https://query1.finance.yahoo.com/v7/finance/chart/CPN.BK?range=2y&interval=1d&indicators=quote&includeTimestamps=true')
output = df[['timestamp','open','high,'low','close']]

请指导如何将数据放入数据框

如果您使用pandas从您的url read_json ,它将把所有json数据保存到一个单元格中(列chart ,行result )。

根据您的代码,您必须为'timestamp','open','high,'low''close'提取字典数据,然后将它们传递给pandas DataFrame

import pandas as pd
df = pd.read_json('https://query1.finance.yahoo.com/v7/finance/chart/CPN.BK?range=2y&interval=1d&indicators=quote&includeTimestamps=true')
data = df['chart']['result'][0]
result = {'timestamp':data['timestamp'],
          'open':data['indicators']['quote'][0]['open'],
          'high':data['indicators']['quote'][0]['high'],
          'low':data['indicators']['quote'][0]['low'],
          'close':data['indicators']['quote'][0]['close']
         }
df1 = pd.DataFrame(result, columns==['timestamp','open','high','low','close'])
df1

df1将是:

    timestamp    open   high    low     close   
0   1442977200   44.50  45.25   44.25   45.00       
1   1443063600   44.75  45.75   44.50   45.00   
2   1443150000   44.75  45.00   44.25   44.50   
3   1443409200   44.25  44.25   43.00   43.00   
4   1443495600   42.50  44.50   42.25   44.00   
5   1443582000   44.25  44.75   43.50   44.75   
6   1443668400   44.50  45.00   44.25   45.00   
7   1443754800   45.00  45.00   44.00   44.25   
8   1444014000   44.25  44.75   43.75   44.50   
...

或者,您可以从url加载json(请参阅此答案 ),然后提取字典数据( 'timestamp','open','high,'low' and 'close' ),并将其传递给pandas以生成结果数据框。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM