Skip to content

Instantly share code, notes, and snippets.

@debboutr
Last active October 26, 2018 17:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save debboutr/b475ea8cbeef36cff13c2c960e434728 to your computer and use it in GitHub Desktop.
Save debboutr/b475ea8cbeef36cff13c2c960e434728 to your computer and use it in GitHub Desktop.
Explode MultiPolygon geometry into individual Polygon geometries in a shapefile using GeoPandas and Shapely
import geopandas as gpd
from shapely.geometry.polygon import Polygon
from shapely.geometry.multipolygon import MultiPolygon
def explode(indata):
indf = gpd.GeoDataFrame.from_file(indata)
outdf = gpd.GeoDataFrame(columns=indf.columns)
for idx, row in indf.iterrows():
if type(row.geometry) == Polygon:
outdf = outdf.append(row,ignore_index=True)
if type(row.geometry) == MultiPolygon:
multdf = gpd.GeoDataFrame(columns=indf.columns)
recs = len(row.geometry)
multdf = multdf.append([row]*recs,ignore_index=True)
for geom in range(recs):
multdf.loc[geom,'geometry'] = row.geometry[geom]
outdf = outdf.append(multdf,ignore_index=True)
outdf = outdf.set_geometry('geometry')
return outdf
@keithfma
Copy link

In case others find their way here, geopandas has this feature built in now:

https://www.pydoc.io/pypi/geopandas-0.4.0/autoapi/geodataframe/index.html#geodataframe.GeoDataFrame.explode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment