使用geopandas生成形状文件时引发ValueError

时间:2016-08-23 11:18:31

标签: python centroid geopandas

我刚刚开始使用shapefile。我有一个shapefile,其中每个对象都是一个多边形。我想生成一个新的shapefile,其中每个多边形的几何形状由其质心代替。有我的代码。

import geopandas as gp
from shapely.wkt import loads as load_wkt

fname = '../data_raw/bg501c_starazagora.shp'
outfile = 'try.shp'
shp = gp.GeoDataFrame.from_file(fname)

centroids = list()
index = list()

df = gp.GeoDataFrame()

for i,r in shp.iterrows():
    index.append(i)
    centroid = load_wkt(str(r['geometry'])).centroid.wkt
    centroids.append(centroid)

df['geometry'] = centroids
df['INDEX'] = index

gp.GeoDataFrame.to_file(df,outfile)

当我运行脚本时,我最终得到raise ValueError("Geometry column cannot contain mutiple " ValueError: Geometry column cannot contain mutiple geometry types when writing to file. 我无法理解有什么不对。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

问题在于,您使用几何体的字符串表示形式而不是形状几何对象填充几何体字段。

无需转换为wkt。你的循环可能是:

for i,r in shp.iterrows():
    index.append(i)
    centroid = r['geometry'].centroid
    centroids.append(centroid)

但是,根本不需要遍历地理数据帧。你可以创建一个新的shapefile质心,如下所示:

df=gp.GeoDataFrame(data=shp, geometry=shp['geometry'].centroid)
df.to_file(outfile)