Python – Delete Rows in GeoDataFrame Based on Geometry Type

geopandaspython

I have a GeoDataFrame object from geopandas with its geometry column and polygons and multipolygons from shapely.geometry.
I want to filter the dataframe and only leaving out the multipolygons.

I tried:

gdf = gdf[gdf["geometry"] == shapely.geometry.multipolygon.MultiPolygon]

I guess it could be something along the lines of "validate" if every value in the geometry column,
is instance of this shapely.geometry.multipolygon.MultiPolygon object.

How could I filter out this GeoDataFrame?

Best Answer

Use the geom_type property:

gdf = gdf[gdf.geom_type == 'MultiPolygon']

Note your question text states "leaving out the multipolygons" but your code means "keeping only the multipolygons". If you actually want to remove the MultiPolygons, the code would be:

gdf = gdf[gdf.geom_type != 'MultiPolygon']

Example:

import geopandas
from geopandas import GeoSeries
from shapely.geometry import Polygon, MultiPolygon

p = Polygon([(0, 0), (1, 0), (1, 1)])
mp = MultiPolygon([
    Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]),
    Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])
])

g = GeoSeries([p, mp])
gdf = geopandas.GeoDataFrame(geometry=g)

print("All records:", gdf)
print("Just MultiPolygons:", gdf[gdf.geom_type == 'MultiPolygon'])
print("No MultiPolygons:", gdf[gdf.geom_type != 'MultiPolygon'])

Output:

All records:                                             geometry
0  POLYGON ((0.00000 0.00000, 1.00000 0.00000, 1....
1  MULTIPOLYGON (((0.00000 0.00000, 1.00000 0.000...

Just MultiPolygons:                                             geometry
1  MULTIPOLYGON (((0.00000 0.00000, 1.00000 0.000...

No MultiPolygons:                                             geometry
0  POLYGON ((0.00000 0.00000, 1.00000 0.00000, 1....
Related Question