python - 如何将这种结构从 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
谢谢
解决方案
你已经很接近了,只是不要自己传递整个响应 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
推荐阅读
- plotly-dash - 破折号下拉菜单图
- java - 如何使用其数据库导出 java jar 文件?
- java - 如何安装或注册 Saxon HE 10.3 配置?未使用配置
- haskell - 退出时恢复终端设置
- regex - 正则表达式:必须只包含字母、数字或字符
- flutter - 如何在 Flutter WebView 中将数据发布到 URL
- python - 在空闲时导入 tensorflow 抛出错误:DLL 加载失败
- python-3.x - 根据数据包中的注释使用 scapy 过滤 PCAP 文件
- html - 将 React 连接到 index.html 以测试 npm 包
- r - 在标识符的值内将重叠的日期时间间隔拆分为不重叠的间隔