I have a polygon shapefile. Which have some numeric attributes (A, B). I clustered the shapefile in five groups (labels) based on an attribute(A) and want to dissolve them while aggregating other attributes (A, B). Code for that is:

import geopandas as gpd
# suppose clustered_df is a gdf obtained after clustering
db_clustered_dissolve = clustered_df .dissolve(by='labels'
            , aggfunc= {'labels':'count','A': 'sum', 'B': 'sum'})

The above code dissolves the dataframe by labels column and create Multi-part polygons.

I know that if I want only single-part polygons then I can use explode() on the dataframe db_clustered_dissolve but I can not accuratly calculate A, B and count for those resulted single part dissolved polygons because every single-part polygon will have same values for A, B and count as their corresponding Multi-part polygons.

I'm having this idea that I can use something that only single-part polygon would be created while dissolving and statistics for those could be calculated on the spot.


You need to dissolve by labels and contiguity to get what you want. Therefore, you first need to identify contiguous components and then do the dissolve. That is a simple operation with libpysal.

Using the example data from geopandas:

import geopandas as gpd
import libpysal

earth = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
earth = earth.explode()  # to get single part input

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

# asssing component labels
earth['comp'] = W.component_labels

dissolved = earth.dissolve(['continent', 'comp'])

See libpysal documentation for more on spatial weights matrices: https://pysal.org/libpysal/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.