Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 971
Kevin Avatar asked Nov 26 '25 00:11

Kevin


1 Answers

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.

like image 69
Dith Avatar answered Nov 28 '25 05:11

Dith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!