我有以下问题:我有一个形状点列表和一个形状多边形列表。 现在,我要检查给定点在哪个多边形中。
此刻,我正在使用以下代码,这似乎不太聪明:
# 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
我可以以某种方式加快速度吗?我有超过100.000点和超过10.000多边形,这些循环需要一段时间。谢谢!
答案 0 :(得分:0)
我知道在注释中可以找到特定问题的解决方案,但是要回答一个有关如何检查点数组是否在多边形内的相关问题,我找到了以下解决方案:
>>> 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])
我不知道这样做可以加快计算速度,但是至少您可以避免for循环。