I have a question. I have a GeoDataFrame object from geopandas with a column named "geometry" and polygons and multipolygons from shapely.geometry. I want to filter the dataframe and only leaving out the multipolygons (knowing that multipolygons are object).
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 Geo/DataFrame?
CodePudding user response:
gdf = gdf.loc[gdf["geometry"].apply(lambda x: type(x) == shapely.geometry.multipolygon.MultiPolygon]
CodePudding user response:
a combination of loc[]
and isinstance()
will filter to just polygons. Full working example below.
import geopandas as gpd
import shapely
world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
world.loc[world["geometry"].apply(lambda g: isinstance(g, shapely.geometry.Polygon))]