python - 如何将 python 中的类转换为 pandas 数据框?

标签 python python-3.x pandas api postman

我正在尝试从 python 中的类对象创建一个 pandas 数据框。

类对象是我从以下教程获得的 postman python 脚本的输出:https://developer.cisco.com/meraki/build/meraki-postman-collection-getting-started/

我想得到这个的输出

print(response.text)

给出:

[{"id":578149602163689207,"name":"Axel Network Test"},{"id":578149602163688579,"name":"Your org"},{"id":578149602163688880,"name":"Your org"},{"id":578149602163688885,"name":"Your org"},{"id":578149602163689038,"name":"Tory's Test Lab"},.......

我想将其放入带有 ID 列和名称列的 pandas 数据框中。

import requests
import pandas as pd

url = "https://api.meraki.com/api/v0/organizations"

headers = {
    'X-Cisco-Meraki-API-Key': "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    'User-Agent': "PostmanRuntime/7.15.0",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Postman-Token': "7d29cb4e-b022-4954-8fc8-95e5361d15ba,1a3ec8cb-5da8-4983-956d-aab45ed00ca1",
    'accept-encoding': "gzip, deflate",
    'referer': "https://api.meraki.com/api/v0/organizations",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, headers=headers)

写累了

df = pd.DataFrame(response, columns=['id', 'name']) 

但这会产生很多错误。

查看错误日志:https://pastebin.com/4BKFYng1

我怎样才能实现我想要的?

最佳答案

由于响应文本在 json 中,您可以:
1. 将json转为dict。
2. 将字典作为数据框提供。

#load the json as a dict
data = json.loads(response.text)

df = pd.DataFrame.from_dict(data, orient='index')
df.reset_index(level=0, inplace=True)

然后您可以更改列的名称或其他任何内容。

关于python - 如何将 python 中的类转换为 pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646636/

相关文章:

python - 如何根据多个值过滤数据框中的单列

python - 我怎样才能更好地编写这些函数以使其有意义

python-3.x - Python 类型、pickle 和序列化

python - 用 python 开始循环

python - value_counts 无法正常工作

用日期范围填充行的 Pythonic 方法

python - R的c()在python中的等价函数是什么?

python - 找不到键盘映射 'Windows Proper Redo"

python - Windows XP - 在 Python 中以编程方式静音/取消静音音频

python - 如何捕捉 Python PyQt5 QTreeWidget 按 Enter(返回)键?