gpt4 book ai didi

python - 使用 pandas 将 JSON 转换为数据框

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:18 24 4
gpt4 key购买 nike

我正在尝试获取数据帧,但在指定文件后,根据我在 read.json 中指定的参数,不断遇到各种错误消息。

我已经浏览了 pandas.read_json 文档中的许多参数,但无法找到解决方案。

import pandas
json_file = "https://gis.fema.gov/arcgis/rest/services/NSS/OpenShelters/MapServer/0/query?where=1%3D1&outFields=*&returnGeometry=false&outSR=4326&f=json"
pandas.read_json(json_file)

我正在尝试获取数据帧,但在指定文件后,根据我在 read.json 中指定的参数,不断遇到各种错误消息。

最佳答案

因为 JSON 不能直接转换为 DataFrameread_json 仅适用于 orient parameter 定义的几种格式。 。您的 JSON 不遵循任何允许的格式,因此您需要在将 JSON 转换为数据帧之前对其进行操作。

让我们深入了解一下您的 JSON:

{
"displayFieldName": ...,
"fieldAliases": {...},
"fields": {...},
"features": [...]
}

我将猜测并假设 features 节点就是您想要的。让我们更深入地了解功能:

"features": [
{
"attributes": {
"OBJECTID": 1,
"SHELTER_ID": 223259,
...
}
},
{
"attributes": {
"OBJECTID": 2,
"SHELTER_ID": 223331,
...
}
},
...
]

features 包含一个对象列表,每个对象都有一个 attributes 节点。 attributes 节点中包含的数据是您真正想要的。

这是代码

import pandas as pd
import json
from urllib.request import urlopen

json_file = "https://gis.fema.gov/arcgis/rest/services/NSS/OpenShelters/MapServer/0/query?where=1%3D1&outFields=*&returnGeometry=false&outSR=4326&f=json"
data = urlopen(json_file).read()
raw_json = json.loads(data)
formatted_json = [feature['attributes'] for feature in raw_json['features']]

formatted_json 现在是包含我们要查找的数据的字典列表。它不再是 JSON。创建数据框:

df = pd.DataFrame(formatted_json)

关于python - 使用 pandas 将 JSON 转换为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56958209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com