【发布时间】:2020-12-03 21:18:31
【问题描述】:
我是 Python 新手,所以我为基本的编程技能道歉,我知道我使用了太多的“循环 for”(来自 Matlab,它拖累了我)。
我有数百万个点(timestep、long、lat、pointID)和数百个不规则的非重叠多边形(vertex_long、vertex_lat、polygonID)。points and polygons format sample
我想知道每个点包含哪个多边形。
我可以这样做:
from matplotlib import path
def inpolygon(lon_point, lat_point, lon_poly, lat_poly):
shape = lon_point.shape
lon_point = lon_point.reshape(-1)
lat_point = lat_point.reshape(-1)
lon_poly = lon_poly.values.reshape(-1)
lat_poly = lat_poly.values.reshape(-1)
points = [(lon_point[i], lat_point[i]) for i in range(lon_point.shape[0])]
polys = path.Path([(lon_poly[i], lat_poly[i]) for i in range(lon_poly.shape[0])])
return polys.contains_points(points).reshape(shape)
然后
import numpy as np
import pandas as pd
Areas_Lon = Areas.iloc[:,0]
Areas_Lat = Areas.iloc[:,1]
Areas_ID = Areas.iloc[:,2]
Unique_Areas = np.unique(Areas_ID)
Areas_true=np.zeros((Areas_ID.shape[0],Unique_Areas.shape[0]))
for i in range(Areas_ID.shape[0]):
for ii in range(Unique_Areas.shape[0]):
Areas_true[i,ii]=(Areas_ID[i]==Unique_Areas[ii])
Areas_Lon_Vertex=np.zeros(Unique_Areas.shape[0],dtype=object)
Areas_Lat_Vertex=np.zeros(Unique_Areas.shape[0],dtype=object)
for i in range(Unique_Areas.shape[0]):
Areas_Lon_Vertex[i]=(Areas_Lon[(Areas_true[:,i]==1)])
Areas_Lat_Vertex[i]=(Areas_Lat[(Areas_true[:,i]==1)])
import f_inpolygon as inpolygon
Areas_in=np.zeros((Unique_Areas.shape[0],Points.shape[0]))
for i in range (Unique_Areas.shape[0]):
for ii in range (PT.shape[0]):
Areas_in[i,ii]=(inpolygon.inpolygon(Points[ii,2], Points[ii,3], Areas_Lon_Vertex[i], Areas_Lat_Vertex[i]))
这样,最终结果 Areas_in Areas_in format 包含与多边形一样多的行和与点一样多的列,其中每一列在点相对于多边形索引的行处为 true=1(第一个给定的多边形 ID -- > 第一行,依此类推)。
代码可以正常工作,但是对于它应该做的事情来说非常缓慢。当在规则网格或点半径内定位点时,我已成功尝试实现 KDtree,这显着提高了速度,但对于不规则的非重叠多边形,我无法做到相同或更快。
我看到了一些相关的问题,但不是询问一个点是什么多边形,而是关于一个点是否在多边形内。
有什么想法吗?
【问题讨论】:
-
你考虑过使用shapely吗?
-
请避免在 SO 上发布图片。尝试发布带有示例输入和所需输出的最小可重现代码。谢谢
-
示例输入在上面的图像中,所需的输出类似于: Point1-Timestep1 = is in AreaX; Point2-Timestep1 = 在AreaX; ...; Point1-TimeStepN = 在AreaX,Point2-TimestepN = 在AreaX; ...; PointN-TimestepN = 在 AreaX 中。
标签: python numpy dataframe polygon point