Skip to content
Advertisement

Remove a Polygon from a MultiPolygon with shapely in Python

I am working with spatial objects in Python using the shapely library. Given a MultiPolygon, I want to remove from it the Polygons which don’t contain an obstacle. However, I haven’t found a way to do this, even though I can get the coordinates from the MultiPolygon just by using the mapping function. I already know which Polygons I want to remove, so there is no problem with identifying them.

Do you have any idea about how to get a sub-Polygon from a given MultiPolygon?

Thanks in advance for your help!

Advertisement

Answer

The MultiPolygon can be directly constructed from a list of polygons. Also, one can directly iterate over the polygons which comprise given multipolygon:

from shapely.geometry import Polygon, MultiPolygon

P1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
P2 = Polygon([(2, 2), (3, 2), (3, 3), (2, 3)])
M = MultiPolygon([P1, P2])

for P in M.geoms:
    print(P)

Now, these two properties enable to use list comprehension in order to filter out only polygons satisfying a certain condition some_condition:

M2 = MultiPolygon([P for P in M if some_condition(P)])
Advertisement