首页 > 解决方案 > 将 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

标签: pythonpandasdataframeurllib

解决方案


这是一个解决方案,您可以尝试一下,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

推荐阅读