I have a large, static list of Shapely Point
s that I want to check against a large list of Shapely Polygon
s, filtering out any polygons that contain one or more of the points.
The polygons do not overlap one another.
The same list of points is checked against all polygons.
A simplified example of the overall shape of the data is pictured below. The real data is magnified to a much larger extent.
Currently, I am using the Python any
and the Shapely contains
functions:
from shapely.geometry.point import Point
from shapely.geometry.polygon import Polygon
# A large list of thousands of points
points: list[Point] = []
# A large list of thousands of polygons
polygons: list[Polygon] = []
...
# Want to speed up this loop, which can take many seconds to complete.
# Retain polygons that do not contain any points.
retained_polygons: list[Polygon] = []
for polygon in polygons:
if not any(polygon.contains(point) for point in points):
retained_polygons.append(polygon)
return retained_polygons
For performance reasons, we were hoping there might be a native method within Shapely that could do this more efficiently. We have thousands of polygons to check against thousands of points, and have profiled slow down to this part of the code.
point.within
against all polygons (instead of looping through polygons and usingpolygon.contains
against all points) you could use a spatial index to narrow the number of polys to check e.g. toblerity.org/rtree/tutorial.html gis.stackexchange.com/a/103066/2856