[英]Find in what polygon is each point
我是 Python 的新手,所以我為基本的編程技能道歉,我知道我使用了太多的“循環”(來自 Matlab,它拖累了我)。
我有數百萬個點(timestep、long、lat、pointID)和數百個不規則的非重疊多邊形(vertex_long、vertex_lat、polygonID)。 點和多邊形格式示例
我想知道每個點包含哪個多邊形。
我能夠這樣做:
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 格式包含與多邊形一樣多的行和與點一樣多的列,其中每列在點相對於多邊形索引的行處為 true=1(第一個給定的多邊形 ID --> 第一行,所以)。
該代碼有效,但對於它應該做的事情非常緩慢。 當在規則網格或點半徑內定位點時,我已成功嘗試實現 KDtree,這會顯着提高速度,但對於不規則的非重疊多邊形,我不能做同樣的事情或任何更快的事情。
我已經看到了一些相關的問題,但不是詢問一個點是什么多邊形,而是關於一個點是否在多邊形內。
請問有什么想法嗎?
您是否嘗試過 Geopandas 空間連接?
使用 pip pip install geopandas
或 conda conda conda install -c conda-forge geopandas
那么您應該能夠將數據讀取為 GeoDataframe
import geopandas
df = geopandas.read_file("file_name1.csv") # you can read shp files too.
right_df = geopandas.read_file("file_name2.csv") # you can read shp files too.
# Convert into geometry column
geometry = [Point(xy) for xy in zip(df['longitude'], df['latitude'])] # Coordinate reference system : WGS84
crs = {'init': 'epsg:4326'}
# Creating a Geographic data frame
left_df = geopandas.GeoDataFrame(df, crs=crs, geometry=geometry)
然后你可以申請 sjoin
jdf = geopandas.sjoin(left_df, right_df, how='inner', op='intersects', lsuffix='left', rsuffix='right')
op中的選項是:
當您連接兩個多邊形和點類型的幾何列時,所有這些都應該在您的情況下執行相同的操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.