how to merge touching polygons with geopandas
Asked Answered
U

2

5

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

Uric answered 27/4, 2021 at 9:48 Comment(1)
How to ask:- stackoverflow.com/help/how-to-askBecause
S
8

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.

Sequent answered 27/4, 2021 at 12:5 Comment(3)
1 year late, but, what's "earth" in this code? this is at code: earth.dissolve(by=components)Loos
@Loos a mistake :). Fixed now.Sequent
Nice, to add a coment for future users, gdf is a geopandas dataframe. Pretty helpful this thread! thanks martinfleis!Loos
D
1

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.

Dougherty answered 24/1, 2023 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.