how to merge touching polygons with geopandas

Viewed 1971

i need to merge all touching polygons from a shapefile with geopandas. So is there a solution for. for example, the image below must be one polygon instead of multiple polygons.

thanks

polygons to merge

1 Answers

It depends on how do you want to treat the data attached to those polygons. If you don't care about them and are interested only in geometries, one option is to dissolve the whole GeoDataFrame and then explode it.

combined_polygons = gdf.dissolve().explode()

However, that may not be the most efficient solution. The best way is to determine contiguity components and dissolve based on those. You can do that with libpysal quite easily.

import libpysal

# create spatial weights matrix
W = libpysal.weights.Queen.from_dataframe(gdf)

# get component labels
components = W.component_labels

combined_polygons = gdf.dissolve(by=components)

The latter will allow you to specify aggfunc in dissolve to manage additional attributes.

Related