【问题标题】:Convert JSON API response to pandas Dataframe将 JSON API 响应转换为 pandas Dataframe
【发布时间】:2017-12-01 19:10:24
【问题描述】:

我正在努力将 JSON API 响应转换为 pandas Dataframe 对象。我已经阅读了类似问题/文档的答案,但没有任何帮助。我最接近的尝试如下:

r = requests.get('https://api.xxx')
data = r.text
df = pd.read_json(data, orient='records')

返回以下格式:

0    {'type': 'bid', 'price': 6.193e-05, ...},

1    {'type': 'bid', 'price': 6.194e-05, ...},

3    {'type': 'bid', 'price': 6.149e-05, ...} etc

数据的原始格式为:

{'abc': [{'type': 'bid', 
          'price': 6.194e-05, 
          'amount': 2321.37952545, 
          'tid': 8577050, 
          'timestamp': 1498649162}, 
         {'type': 'bid', 
          'price': 6.194e-05, 
          'amount': 498.78993587,
          'tid': 8577047, 
          'timestamp': 1498649151},
          ...]}

我很高兴被引导到好的文档。

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    我觉得你需要json_normalize:

    from pandas import json_normalize 
    
    df = json_normalize(d, 'abc')
    print (df)
            amount     price      tid   timestamp type
    0  2321.379525  0.000062  8577050  1498649162  bid
    1   498.789936  0.000062  8577047  1498649151  bid
    

    对于多个键,可以使用 concatlist comprehensionDataFrame 构造函数:

    d =  {'abc': [{'type': 'bid', 'price': 6.194e-05, 'amount': 2321.37952545, 'tid': 8577050, 'timestamp': 1498649162}, {'type': 'bid', 'price': 6.194e-05, 'amount': 498.78993587, 'tid': 8577047, 'timestamp': 1498649151}],
          'def': [{'type': 'bid', 'price': 6.194e-05, 'amount': 2321.37952545, 'tid': 8577050, 'timestamp': 1498649162}, {'type': 'bid', 'price': 6.194e-05, 'amount': 498.78993587, 'tid': 8577047, 'timestamp': 1498649151}]}
    

    df = pd.concat([pd.DataFrame(v) for k,v in d.items()], keys=d)
    print (df)
                amount     price      tid   timestamp type
    abc 0  2321.379525  0.000062  8577050  1498649162  bid
        1   498.789936  0.000062  8577047  1498649151  bid
    def 0  2321.379525  0.000062  8577050  1498649162  bid
        1   498.789936  0.000062  8577047  1498649151  bid
    

    【讨论】:

    • 什么是d:df = json_normalize(d, 'abc')
    • d 是 API 响应,在发布的问题中是 r。
    猜你喜欢
    • 2017-04-13
    • 2021-03-29
    • 1970-01-01
    • 2017-04-27
    • 2020-11-03
    • 1970-01-01
    • 2019-06-09
    • 2017-01-08
    相关资源
    最近更新 更多