我正在尝试根据日期绘制此 json 中的数据。如何将数据框的“created_at”日期转换为 int?获取类型错误:列表索引必须是整数或切片,而不是 strimport requestsimport pandas as pdimport datetimeimport matplotlib.pyplot as plt%matplotlib inlineurl = 'https://api.oilpriceapi.com/v1/prices/past_week'headers = {'Authorization': 'Token XXXXXXXXXXX','Content-Type': 'application/json'}response = requests.get(url = url, headers = headers)data = response.json()print(data)dates = (data['data']['prices']['created_at'])values = (data['data']['prices']['price'])df = pd.DataFrame({'dates':dates, 'values':values})df['dates'] = [pd.to_datetime(i) for i in df['dates']]plt.line(dates, values)错误:TypeError Traceback (most recent call last)<ipython-input-9-db4fdff870ee> in <module>() 14 print(data) 15 ---> 16 dates = (data['data']['prices']['created_at']) 17 values = (data['data']['prices']['price']) 18 TypeError: list indices must be integers or slices, not strJSON:{'status': 'success', 'data': {'prices': [{'price': 32.5, 'formatted': '$32.50', 'currency': 'USD', 'code': 'BRENT_CRUDE_USD', 'created_at': '2020-05-27T16:04:00.466Z', 'type': 'spot_price'},......
2 回答
MYYA
TA贡献1868条经验 获得超4个赞
让我给你一个轻微的修正。首先你可以得到dates和prices如下
dates = [item['created_at'] for item in data['data']['prices']]
values = [item['price'] for item in data['data']['prices']]
其他应该按您的预期工作。
qq_笑_17
TA贡献1818条经验 获得超7个赞
这是列表中的字典:
data['data']['prices']
>>[{'price': 32.5,'formatted': '$32.50','currency': 'USD','code': 'BRENT_CRUDE_USD','created_at': '2020-05-27T16:04:00.466Z','type': 'spot_price'}]
因此尝试
data['data']['prices'][0]['created_at']
添加回答
举报
0/150
提交
取消