python - 将 API 响应转换为 Pandas DataFrame
问题描述
我使用以下代码进行 API 调用:
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
string = response.read().decode('utf-8')
json_obj = json.loads(string)
它返回以下内容:
{"forecast": [17.588294043898163, 17.412641963452206],
"index": [
{"SaleDate": 1629417600000, "Type": "Type 1"},
{"SaleDate": 1629504000000, "Type": "Type 2"}
]
}
如何将此 api 响应转换为 Panda DataFrame 以在 Pandas 数据框中转换以下格式的字典
Forecast SaleDate Type
17.588294043898163 2021-08-16 Type 1
17.412641963452206 2021-08-17 Type 1
解决方案
这是一个解决方案,您可以尝试一下,list comprehension
用于展平数据。
import pandas as pd
flatten = [
{"forecast": j, **resp['index'][i]} for i, j in enumerate(resp['forecast'])
]
pd.DataFrame(flatten)
forecast SaleDate Type
0 17.588294 1629417600000 Type 1
1 17.412642 1629504000000 Type 2
推荐阅读
- javascript - 让 react-dropzone 接受 *all* 文件
- c# - 如何为所有控件、面板、文本块等设置背景属性?
- r - 在数据框中创建变量的正则表达式循环
- batch-file - 批处理字符串中的空格
- azure-devops - 如何在托管环境中进行代码签名和运行安装程序?
- angular - 通过将数据关联到每个用户来扩展 Angular Firestore 应用程序
- microsoft-graph-api - Daemon application gets an App-only access token with no Roles
- kubernetes - DigitalOcean Loadbalancer behavior Kubernetes TCP 443
- python - matplotlib: why plot a hist would cause IndexError in python?
- javascript - 在一年中的某个日期更改变量