【问题标题】:python: read json with pandaspython:用熊猫读取json
【发布时间】:2018-03-04 23:32:56
【问题描述】:

我想为下面的 json 链接获取时间戳、高、低、打开、关闭,但我只得到错误 charterror 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']]

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

【问题讨论】:

    标签: python json


    【解决方案1】:

    如果您从您的网址使用pandasread_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(参考this answer),然后提取字典数据('timestamp','open','high,'low' and 'close'),将其传递给 pandas 以生成结果数据帧。

    【讨论】:

    • 谢谢。如何使用时间戳从左侧开始对数据帧进行排序,然后是打开、高、低和关闭。现在它开始了,关闭,跟随高,低,打开和时间戳。需要正确的顺序。
    • @lotteryman,在 pd.DataFrame 中添加列,检查更新的答案:df1 = pd.DataFrame(result, columns==['timestamp','open','high','low','close'])
    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 2019-03-31
    • 2017-03-28
    • 2014-05-11
    • 2016-12-26
    • 2020-08-26
    • 2021-11-11
    相关资源
    最近更新 更多