我有一个 shapefile(以下将称为源文件),我需要通过多多边形 shapefile 对其进行剪辑,以便我可以为每个多边形都有一个剪辑的 shapefile。我尝试了 geopandas,尽管我可以通过从多多边形形状文件中单独选择多边形来单独剪切源文件来剪切源文件,但是当我尝试循环多边形以自动执行剪切过程时,我得到以下结果错误:
错误:
类型错误:“掩码”应该是 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)
最佳答案
两点
- https://geopandas.org/en/stable/docs/reference/api/geopandas.clip.html mask 可以是 GeoDataFrame 因此不需要循环
- https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html生成索引值的元组和行的命名元组。因此,您的错误是您将此 tuple 传递给
clip()
已经构建了一个示例。使用 GeoDataFrame 作为 mask 进行剪辑要简单得多。
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)
关于python - 在 geopandas 中使用多多边形 shapefile 剪切 shapefile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71899858/