Combine Multiple Polygons into a Single Polygon with Holes Using Python

geopandaspolygonpythonshapely

I have the following GeoDataFrame with multiple polygons which represents a single area (raster_val = 1.0) with holes in the middle (raster_val = NaN):

                                       geometry           raster_val
0   POLYGON ((8.77500 47.70000, 8.77500 47.67500, ...         NaN
1   POLYGON ((8.90000 47.40000, 8.90000 47.30000, ...         NaN
...
9   POLYGON ((6.12500 46.27500, 6.12500 46.25000, ...         1.0
10  POLYGON ((8.57500 47.80000, 8.57500 47.77500, ...         1.0
11  POLYGON ((8.90000 45.85000, 8.90000 45.82500, ...         1.0

I would like to combine polygons corresponding to raster_val = 1.0 into a single Polygon/Multipolygon but preserving the holes indicated by the polygons with raster_val = NaN.

I've already tried geopandas dissolve() method:

polygons = polygons.dissolve(by='raster_val')

This combines raster_val = 1.0 polygons but it ignores all raster_val = NaN polygons so the combined multipolygon doesn't have any holes. Do you have any suggestions on how to include those NaN holes?

Best Answer

Perhaps shapely's unary_union will help, where df is your GeoDataFrame:

import pandas as pd
from shapely.ops import unary_union

hole_indx = pd.isna(df.raster_val)

holes = unary_union(df.loc[hole_indx, 'geometry'])
polys = unary_union(df.loc[~hole_indx, 'geometry'])

polys_and_holes = polys.difference(holes)
Related Question