我有一个shapefile (以后将被称为源文件),我需要用一个多多边形的shapefile来剪辑它,这样我就可以为每个多边形剪裁一个shapefile。我尝试了geopandas,虽然我能够通过从多个多边形文件中分别选择多边形来裁剪源文件,但是当我试图在多边形上循环以自动化裁剪过程时,我会得到以下错误:
错误: TypeError:“掩码”应该是GeoDataFrame,GeoSeries或(多)多边形,得到
代码:
import geopandas as gpd
source = ('source-shapefile.shp')
mask = ('mask_shapefile.shp')
sourcefile = gpd.read_file(source)
maskfile = gpd.read_file(mask)
for row in maskfile.iterrows():
gpd.clip(sourcefile, row)发布于 2022-04-17 18:31:24
最后,经过5个小时的研究,我现在可以剪辑多多边形形状文件,并保存分别与他们各自的名字剪裁多边形。下面的代码可能很脏,但可以工作。代码:
import geopandas as gpd
import pandas as pd
import os, sys
source = ('source-shapefile.shp')
mask = ('mask_shapefile.shp')
outpath = ('/outpath')
sourcefile = gpd.read_file(source)
maskfile = gpd.read_file(mask)
clipshape = maskfile.explode()
clipshape.set_index('CATCH_NAME', inplace=True) # CATCH_NAME is attribute column name
for index, row in clipshape['geometry'].iteritems():
clipped = gpd.clip(sourcefile, row)
clipped.to_file(os.path.join(outpath, f'{index}.shp'))发布于 2022-04-17 07:13:18
两点
clip()元组传递给了
已经建立了一个例子。使用GeoDataFrame作为掩码进行剪辑要简单得多。
import geopandas as gpd
import pandas as pd
# lets build a mask for use in clip, multipolygons and polygons
maskfile = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
maskfile = maskfile.loc[maskfile["continent"].eq("Europe") & maskfile["name"].ne("Russia")].pipe(
lambda d: d.assign(gdp_grp=pd.cut(d["gdp_md_est"], bins=4, labels=list("abcd")))
).dissolve("gdp_grp").reset_index()
sourcefile = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
# now clip, no looping needed
gpd.clip(sourcefile, maskfile)https://stackoverflow.com/questions/71899858
复制相似问题