Kevin
Kevin

Reputation: 191

How to check if any point from a list of points is contained by any polygon from a list of polygons?

I have the following problem: I have a list of shapely points and a list of shapely polygons. Now I want to check in which polygon a given point is.

At the moment I am using the following code, which seems not very clever:


# polygons_df is a pandas dataframe that contains the geometry of the polygons and the usage of the polygons (landuses in this case, e.g. residential)

# point_df is a pandas dataframe that contains the geometry of the points and the usage of the point (landuses in this case, e.g. residential)

# polylist is my list of shapely polygons

# pointlist is my list of shapely points 

from shapely.geometry import Point, Polygon
import pandas as pd
import geopandas as gpd

i = 0
while i < len(polygons_df.index):
    j = 0
    while j < len(point_df.index):
        if polylist[i].contains(point):
            point.at[j, 'tags.landuse'] = polygons_df.iloc[i]['tags.landuse']
        else:
            pass
        j += 1
    i += 1

Can I somehow speed this up? I have more than 100.000 points and more than 10.000 polygons and these loops take a while. Thanks!

Upvotes: 3

Views: 3225

Answers (1)

Dith
Dith

Reputation: 151

I know a solution was found in the comments for the particular problem, but to answer a related question of how to check if an array of points is inside a shapely Polygon, I found the following solution:

>>> poly = Polygon([(0,0), (1,0), (0,1)])
>>> contains = np.vectorize(lambda p: poly.contains(Point(p)), signature='(n)->()')
>>> contains(np.array([[0.5,0.49],[0.5,0.51],[0.5,0.52]]))
array([ True, False, False])

I don't know that this neccesarily speeds up the calculations, but at least you can avoid the for-loop.

Upvotes: 1

Related Questions