diff --git a/geopandas/tests/test_overlay.py b/geopandas/tests/test_overlay.py index 1b8c3a0..f145893 100644 --- a/geopandas/tests/test_overlay.py +++ b/geopandas/tests/test_overlay.py @@ -628,6 +628,38 @@ def test_keep_geom_type_geometry_collection2(): assert_geodataframe_equal(result1, expected1) +def test_keep_geom_type_geomcoll_different_types(): + polys1 = [box(0, 1, 1, 3), box(10, 10, 12, 12)] + polys2 = [ + Polygon([(1, 0), (3, 0), (3, 3), (1, 3), (1, 2), (2, 2), (2, 1), (1, 1)]), + box(11, 11, 13, 13), + ] + df1 = GeoDataFrame({"left": [0, 1], "geometry": polys1}) + df2 = GeoDataFrame({"right": [0, 1], "geometry": polys2}) + result1 = overlay(df1, df2, keep_geom_type=True) + expected1 = GeoDataFrame( + { + "left": [1], + "right": [1], + "geometry": [box(11, 11, 12, 12)], + } + ) + assert_geodataframe_equal(result1, expected1) + + result2 = overlay(df1, df2, keep_geom_type=False) + expected2 = GeoDataFrame( + { + "left": [0, 1], + "right": [0, 1], + "geometry": [ + GeometryCollection([LineString([(1, 2), (1, 3)]), Point(1, 1)]), + box(11, 11, 12, 12), + ], + } + ) + assert_geodataframe_equal(result2, expected2) + + def test_keep_geom_type_geometry_collection_difference(): # GH 2163 diff --git a/geopandas/tools/overlay.py b/geopandas/tools/overlay.py index 78484e3..babb67a 100644 --- a/geopandas/tools/overlay.py +++ b/geopandas/tools/overlay.py @@ -343,16 +343,18 @@ def overlay(df1, df2, how="intersection", keep_geom_type=None, make_valid=True): orig_num_geoms_exploded = exploded.shape[0] if geom_type in polys: - exploded = exploded.loc[exploded.geom_type.isin(polys)] + exploded.loc[~exploded.geom_type.isin(polys), geom_col] = None elif geom_type in lines: - exploded = exploded.loc[exploded.geom_type.isin(lines)] + exploded.loc[~exploded.geom_type.isin(lines), geom_col] = None elif geom_type in points: - exploded = exploded.loc[exploded.geom_type.isin(points)] + exploded.loc[~exploded.geom_type.isin(points), geom_col] = None else: raise TypeError( "`keep_geom_type` does not support {}.".format(geom_type) ) - num_dropped_collection = orig_num_geoms_exploded - exploded.shape[0] + num_dropped_collection = ( + orig_num_geoms_exploded - exploded.geometry.isna().sum() + ) # level_0 created with above reset_index operation # and represents the original geometry collections