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

2024-06-06 11:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python中的类对象创建pandas数据帧。在

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

我想看看这个的输出

print(response.text)

它给出了:

^{pr2}$

我想把它放入一个pandas dataframe,其中有and ID列和name列。在

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

我怎样才能达到我想要的?在


Tags: 对象namehttpsimportcomapiurlcache
3条回答

由于响应文本在json中,您可以:
1将json转换为dict。
2将dict作为数据帧输入。在

#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)

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

试试这个:

df = pd.DataFrame.from_dict(response.json())

而不是这样:

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

read_json接受JSON字符串或类似JSON文件的对象。在

In [10]: import pandas as pd    

In [11]: df = pd.read_json(response.text)

In [12]: df
Out[12]:
                   id               name
0  578149602163689207  Axel Network Test
1  578149602163688579           Your org
2  578149602163688880           Your org
3  578149602163688885           Your org
4  578149602163689038    Tory's Test Lab

相关问题 更多 >