9

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")]
2
  • Is that slow or what is the problem?
    – BERA
    Oct 13, 2021 at 8:26
  • It's a bit slow (because it has to parse as strings the whole list of points in the geometry) but I could not find any other way. I guess there is no "official"/built-in way of doing this, right?
    – baggiponte
    Oct 13, 2021 at 8:37

2 Answers 2

11

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...
2
  • As usually @gene aggregates all the possible approaches. Thank you :)
    – Taras
    Oct 13, 2021 at 10:42
  • Thank you, this is really great! I did not know geopandas had this great attribute(s). And thank you for the thorough reply!
    – baggiponte
    Oct 14, 2021 at 8:05
11

Using geometry.type=="MULTIPOLYGON" is (15 times in my computer) faster.

at_geometries[at_geometries.geometry.type=="MULTIPOLYGON"]`
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.