Estoy luchando para convertir una respuesta de la API JSON en un objeto Dataframe de pandas. He leído respuestas a preguntas / documentación similares, pero nada me ha ayudado. Mi bash más cercano está abajo:
r = requests.get('https://api.xxx') data = r.text df = pd.read_json(data, orient='records')
Que devuelve el siguiente formato:
0 {'type': 'bid', 'price': 6.193e-05, ...}, 1 {'type': 'bid', 'price': 6.194e-05, ...}, 3 {'type': 'bid', 'price': 6.149e-05, ...} etc
El formato original de los datos es:
{'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}, ...]}
Estoy feliz de ser dirigido a una buena documentación.
Creo que necesitas 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
Para varias claves es posible usar concat
con la list comprehension
y el constructor DataFrame
:
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