Jake
Jake

Reputation: 77

how to merge touching polygons with geopandas

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

Upvotes: 5

Views: 7214

Answers (2)

Degux
Degux

Reputation: 53

Struggled with the same problem and dissolve / explode didn't seem to work.

I finally had the idea to inflate the touching polygons, unite them and then deflate them again:

gdf.geometry.buffer(0.1).unary_union.buffer(-0.1)

This works fine for me. I hope in the future GeoPandas will include the option of merging polygons that only share edges and don't overlap.

Upvotes: 1

martinfleis
martinfleis

Reputation: 7804

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.

Upvotes: 8

Related Questions