如何保存含多个几何列的GeoDataFrame为GeoJSON或CSV文件?
问题根因
GeoJSON格式规范仅支持单默认几何列,你的GeoDataFrame同时存在geometry、centroid、boundary三个geometry dtype的列,超出GeoJSON驱动的解析支持范围,因此触发类型报错;仅保留默认geometry列和非几何的area列时符合格式要求,可正常保存。
解决方案
1. 多几何列GeoJSON保存方法
如需在GeoJSON中保留centroid、boundary信息,可先将非默认几何列转为WKT字符串格式后再保存:
# 转换centroid、boundary为WKT字符串 df["centroid"] = df["centroid"].to_wkt() df["boundary"] = df["boundary"].to_wkt() # 执行保存 df.to_file("result.geojson", driver="GeoJSON")
后续读取该GeoJSON文件后,再将两列转回几何类型即可。
2. CSV读取后多列转几何类型
读取CSV后centroid、boundary默认识别为字符串类的object类型,使用geopandas.GeoSeries.from_wkt方法即可转换为标准几何类型:
import geopandas as gpd # 读取CSV文件 gdf = gpd.read_file("result.csv") # 转换centroid列为几何类型,保持和默认几何列相同的CRS gdf["centroid"] = gpd.GeoSeries.from_wkt(gdf["centroid"], crs=gdf.crs) # 转换boundary列为几何类型 gdf["boundary"] = gpd.GeoSeries.from_wkt(gdf["boundary"], crs=gdf.crs)
如需切换默认激活的几何列,可调用set_geometry方法:
# 切换默认几何列为centroid gdf = gdf.set_geometry("centroid")
注意事项
如果保存时使用的是WKB二进制格式存储几何列,替换上述转换方法为from_wkb即可。
内容的提问来源于stack exchange,提问作者minmarsh
相关产品推荐
相关产品推荐

