How can i convert this from json to pandas
import json
import pandas as pd
import requests
from pandas import json_normalize
url = ("https://api.compound.finance/api/v2/market_history/graph? asset=0xf5dce57282a584d2746faf1593d3121fcac444dc&min_block_timestamp=1566747900&max_block_timestamp=1569339000&num_buckets=10")
headers = {
'Content-Type': 'application/json'
}
res = requests.get(url, headers=headers)
res = requests.get(url).json()
when i call res i get this
{'asset': '0xf5dce57282a584d2746faf1593d3121fcac444dc',
'borrow_rates': [{'block_number': 8234445,
'block_timestamp': 1566747900,
'rate': 0.2037838374151179},
{'block_number': 8254149,
'block_timestamp': 1567007010,
'rate': 0.19253549746358395},
{'block_number': 8273853,
'block_timestamp': 1567266120,
'rate': 0.18496820157299473},
{'block_number': 8293557,
'block_timestamp': 1567525230,
'rate': 0.18374286648370425},
{'block_number': 8313261,
'block_timestamp': 1567784340,
'rate': 0.1804081601042204},
{'block_number': 8332966,
When i try to convert it to dataframe with this code i an get error
df = pd.DataFrame(url['borrow_rates'])
df.set_index('name', inplace = True)
`TypeError Traceback (most recent call last)
<ipython-input-107-a50b20c714a8> in <module>
----> 1 df = pd.DataFrame(url['borrow_rates'])
2 df.set_index('name', inplace = True)
TypeError: string indices must be integers`
So how can i turn this json data into a dataframe. Thanks
CodePudding user response:
It looks like a typo - when you write
df = pd.DataFrame(url['borrow_rates'])
it should be
df = pd.DataFrame(res['borrow_rates']) # res instead of url
the url
variable is just a string while res
is your object, hence the error.