3

The proposed answer here: Filtering by geometry type in GeoPandas

does not answer my question because it only focuses on filtering by one geometric type at a time; I am trying to do so with a list of geometric types.

I am dealing with OpenStreetMap data using the pyrosm package, which can filter a pbf file and load it as a geodataframe. However, some of the datasets contain multiple geometric types (e.g., MultiLineString, LineString, MultiPolygon, Polygon).

In dealing with boundaries, I'd like to keep the geodataframe to only MultiPolygon and Polygon. I've tried this:

boundaries = osm.get_boundaries()  # generate the gdf
boundaries = boundaries[boundaries.geometry.type in ['MultiPolygon', 'Polygon']]

Then I output it to a geopackage.

That doesn't throw any error, but leaves the LineStrings and MultiLineStrings in the output.

How do I catch MultiPolygons and Polygons and exclude multiple others?

1
  • 1
    @BERA Sorry about that, just an oversight on my part. Marked as correct. Thanks!
    – auslander
    Commented Dec 18, 2023 at 14:12

1 Answer 1

1

You can use .loc with geometryType:

import shapely
import geopandas as gpd

L = ["MultiPolygon (((764858 7194069, 764858 7195559, 767965 7195559, 767965 7194069, 764858 7194069)))",
     "MultiLineString ((771497 7194729, 775263 7189643, 777050 7191707))",
     "LineString (765267 7198542, 765786 7193504)",
     "Polygon ((763786 7197801, 762785 7191985, 769787 7195764, 763786 7197801))"]

df = gpd.GeoDataFrame(geometry=[shapely.wkt.loads(x) for x in L], crs="EPSG:3006")
#                                             geometry
# 0  MULTIPOLYGON (((764858.000 7194069.000, 764858...
# 1  MULTILINESTRING ((771497.000 7194729.000, 7752...
# 2  LINESTRING (765267.000 7198542.000, 765786.000...
# 3  POLYGON ((763786.000 7197801.000, 762785.000 7...

df = df.loc[df.apply(lambda x: x.geometry.geometryType() in("MultiPolygon","Polygon"), axis=1)]
#                                             geometry
# 0  MULTIPOLYGON (((764858.000 7194069.000, 764858...
# 3  POLYGON ((763786.000 7197801.000, 762785.000 7...

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.