如何将geopandas dataframe与多个多边形转换为geojson?

0md85ypi  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(225)

我有一个Geopandas数据框与多多边形几何。现在,我想将数据框转换为geojson。因此,我将 Dataframe 转换为dict,然后使用json.dump(dict)将 Dataframe 转换为json。当我有一个多边形时,这很好用,但当几何列有多个多边形时,会抛出错误TypeError: Object of type MultiPolygon is not JSON serializable。什么是最好的转换geopandas dataframe到jsonseraliazble几何是多边形或多边形。

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
bvjveswy

bvjveswy1#

你可以使用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]]]]}}]}

相关问题