将JSON API响应转换为pandas Dataframe

时间:2017-06-28 12:16:24

标签: python json pandas

我正在努力将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},
          ...]}

我很高兴能够获得良好的文档。

1 个答案:

答案 0 :(得分:8)

我认为你需要json_normalize

from pandas.io.json 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