将JSON加载到GeoDataFram中

2024-10-01 09:18:02 发布

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

我很难将下面包含GIS数据(https://data.cityofnewyork.us/resource/5rqd-h5ci.json)的JSON加载到GeoDataFrame中。在

当我尝试设置几何体时,以下代码失败。在

import requests
import geopandas as gpd
data = requests.get("https://data.cityofnewyork.us/resource/5rqd-h5ci.json")
gdf = gpd.GeoDataFrame(data.json())
gdf = gdf.set_geometry('the_geom')
gdf.head()

Tags: 数据httpsimportjsondatarequestsresourceus
3条回答

使用从pandas和本机GeoDataFrame.from_features继承的常规数据帧函数的一种更惯用的方法:

gdf = gpd.GeoDataFrame(data.json())

# features column does not need to be stored, this is just for illustration
gdf['features'] = gdf['the_geom'].apply(lambda x: {'geometry': x, 'properties': {}})
gdf2 = gpd.GeoDataFrame.from_features(gdf['features'])

gdf = gdf.set_geometry(gdf2.geometry)
gdf.head()

对于使用web地图库的人。。。在

如果GeoJSON被包装在FeatureCollection中,就像web映射库(在我的例子中,是单张)导出到GeoJSON字符串时一样,那么您只需将位于features的列表传递给from_features(),如下所示:

import geopandas as gpd
study_area = json.loads("""
 {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[36.394272, -18.626726], [36.394272, -18.558391], [36.489716, -18.558391], [36.489716, -18.626726], [36.394272, -18.626726]]]}}]}
""")
gdf = gpd.GeoDataFrame.from_features(study_area["features"])
print(gdf.head())

输出:

^{pr2}$

别紧张。在

设置几何体失败,因为geopandas.GeoDataFrame构造函数似乎没有被构建为将JSON对象作为python数据结构来处理。因此,它抱怨参数不是有效的几何体对象。你必须把它解析成geopandas.GeoDataFrame能理解的东西,比如shapely.geometry.shape。以下是我这方面运行正常的Python 3.5.4:

#!/usr/bin/env python3

import requests
import geopandas as gpd
from shapely.geometry import shape

r = requests.get("https://data.cityofnewyork.us/resource/5rqd-h5ci.json")
r.raise_for_status()

data = r.json()
for d in data:
    d['the_geom'] = shape(d['the_geom'])

gdf = gpd.GeoDataFrame(data).set_geometry('the_geom')
gdf.head()

免责声明:我对Geo一无所知。直到我安装了geopandas来解决这个问题并阅读了一些在线文档之前,我甚至不知道这些库和这种数据的存在。在

相关问题 更多 >