[英]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.