1

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?

0

1 Answer 1

0

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 that you have read and understand our privacy policy and code of conduct.

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