首页 > 解决方案 > 如何将这种结构从 API 转换为 python Dataframe

问题描述

我从 API 获得了这个结果,但我无法将此结构转换为 python pandas Dataframe。

来自 API 的响应

response = {'lists': [{'id': '0d4348d3a7', 'name': 'list one'}, {'id': '5e3e22ae7b', 'name': 'list two'}], 'total_items' : 2}

试一试

df = pd.DataFrame(response)
print(df)
                                                   lists  total_items
    0  {'id': '0d4348d3a7', 'name': 'list one'            2
    1  {'id': '5e3e22ae7b', 'name': 'list two...          2

不正是我想要的。

试试两个

df = json.loads(response)
print(df)

Raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not dict

谢谢

标签: pythondataframe

解决方案


你已经很接近了,只是不要自己传递整个响应 json,而只传递你需要的值:

>>> import pandas as pd
>>> response = {'lists': [{'id': '0d4348d3a7', 'name': 'list one'}, {'id': '5e3e22ae7b', 'name': 'list two'}], 'total_items': 2}
>>> df = pd.DataFrame(response["lists"])
>>> df
           id      name
0  0d4348d3a7  list one
1  5e3e22ae7b  list two

推荐阅读