1

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?

  • 1
    Cant you use Difference after your dissolve with a dataframe of raster_val is NaN as "erase" features? – BERA Feb 11 at 9:05
0

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)

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.