如何将具有多多边形的geopandas数据框转换为geojson?

问题描述 投票:0回答:2

我有一个具有多多边形几何形状的 Geopandas 数据框。现在,我想将数据框转换为 geojson。因此,我将数据帧转换为

dict
,然后使用
json.dump(dict)
将数据帧转换为 json。当我有单个多边形时,这很有效,但当几何列有多个多边形时,会抛出错误
TypeError: Object of type MultiPolygon is not JSON serializable
。无论几何图形是多多边形还是多边形,将 geopandas 数据框转换为
json
seraliazble
的最佳方法是什么。

df=
location    geometry    
1          MULTIPOLYGON (((-0.304766 51.425882, -0.304904...    
2          MULTIPOLYGON (((-0.305968 51.427425, -0.30608 ...    
3          MULTIPOLYGON (((-0.358358 51.423471, -0.3581 5...    
4          MULTIPOLYGON (((-0.357654 51.413925, -0.357604...

list_data = df.to_dict(orient='records')
print(json.dumps(list_data))

错误:-

TypeError: Object of type MultiPolygon is not JSON serializable
python json geojson geopandas multipolygons
2个回答
2
投票

您可以使用geopandas.GeoDataFrame.to_json

类似这样的:

import geopandas as gpd
from shapely.geometry import MultiPolygon, Polygon
p1 = Polygon([(0, 0), (1, 0), (1, 1)])
p2 = Polygon([(5, 0), (6, 0), (6, 1)])
p3 = Polygon([(10, 0), (11, 0), (11, 1)])

d = {'number': [1, 2], 'geometry': [MultiPolygon([p1, p2]), MultiPolygon([p2, p3])]}
gdf = gpd.GeoDataFrame(d, crs="EPSG:31370")
print(gdf.to_json())

结果:

{"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {"number": 1}, "geometry": {"type": "MultiPolygon", "coordinates": [[[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]], [[[5.0, 0.0], [6.0, 0.0], [6.0, 1.0], [5.0, 0.0]]]]}}, {"id": "1", "type": "Feature", "properties": {"number": 2}, "geometry": {"type": "MultiPolygon", "coordinates": [[[[5.0, 0.0], [6.0, 0.0], [6.0, 1.0], [5.0, 0.0]]], [[[10.0, 0.0], [11.0, 0.0], [11.0, 1.0], [10.0, 0.0]]]]}}]}

0
投票

您可以将地理数据框转换为字典

geo_dict = gdf.__geo_interface__  #this will make a propper dict

然后使用 json.dumps

另一种方法是使用

gdf.to_file('dataframe.geojson', driver='GeoJSON') #this will export a geojson file to your directory 
© www.soinside.com 2019 - 2024. All rights reserved.