GeoPandas MultiPolygon Clipping – Clipping Shapefile with MultiPolygon Shapefile in GeoPandas

clipgeopandasmulti-polygonpythonshapefile

I have a shapefile (will be called source-file hereafter), which I need to clip by a MultiPolygon shapefile so that I can have a clipped shapefile for each polygon.

I tried the GeoPandas, though I am able to clip the source file by individually clipping it by selecting the polygons separately from the MultiPolygon shapefile, when I try to loop over the polygons to automate the clipping process I get the following error:

Error: TypeError: 'mask' should be GeoDataFrame, GeoSeries
or(Multi)Polygon, got <class 'tuple'>

My code:

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)

Best Answer

Finally, I am now able to clip the shapefile by a MultiPolygon shapefile and save the clipped polygons separately with their respective names. The following code works:

import os, sys
import pandas as pd
import geopandas as gpd

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'))