Python – Filtering by Geometry Type in GeoPandas

filtergeometrygeopandaspythonshapely

I have a GeoPandas GeoDataFrame with a geometry column that contains both POLYGONs and MULTIPOLYGONs. How do I filter only MULTIPOLYGONs?

I used this approach, but I am sure there might be better ones:

# 'at' because it's data about Austria
at_geometries.loc[at_geometries["geometry"].astype("str").str.startswith("MULTI")]

Best Answer

There are many solutions (see How to filter a geodataframe by geometry type? for example)

With .loc as you but with geometry.type or geom_type

gdf0 = gdf.loc[gdf.geometry.geometry.type=='MultiPolygon']
gdf0
    ID                 geometry
0    1  MULTIPOLYGON (((244697.452 1000369.231, 244827...
1    5  MULTIPOLYGON (((244912.829 1000603.336, 245042...
2    8  MULTIPOLYGON (((244732.568 1000040.313, 244862...

gdf0= gdf.loc[gdf.geometry.geom_type=='MultiPolygon']
idem

With apply,lambda and type

gdf1 = gdf[gdf.geometry.apply(lambda x : x.type=='MultiPolygon')]
gdf1
    ID                 geometry
0    1  MULTIPOLYGON (((244697.452 1000369.231, 244827...
1    5  MULTIPOLYGON (((244912.829 1000603.336, 245042...
2    8  MULTIPOLYGON (((244732.568 1000040.313, 244862...

With geom_type

gdf2 = gdf[gdf.geom_type=='MultiPolygon']
gdf2
    ID                 geometry
0    1  MULTIPOLYGON (((244697.452 1000369.231, 244827...
1    5  MULTIPOLYGON (((244912.829 1000603.336, 245042...
2    8  MULTIPOLYGON (((244732.568 1000040.313, 244862...

With geometry.type as Kadir Şahbaz

gdf3 = gdf[gdf.geometry.type=="MultiPolygon"]
gdf3
    ID                 geometry
0    1  MULTIPOLYGON (((244697.452 1000369.231, 244827...
1    5  MULTIPOLYGON (((244912.829 1000603.336, 245042...
2    8  MULTIPOLYGON (((244732.568 1000040.313, 244862...