Last active
October 26, 2018 17:14
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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