GeoPandas在引擎盖下使用了优美的外观。为了得到最近的邻居,我使用了nearest_points
from shapely。但是,该方法不包括k-最近点
我需要计算从到地理数据框最近点的距离,并将距离插入到包含“从该点”数据的地理数据框中
这是我使用GeoSeries.distance()
而不使用其他包或库的方法。请注意,当k == 1
时,返回值基本上显示到最近点的距离There is also a GeoPandas-only solution for nearest point by @cd98 which inspired my approach
这对我的数据很有效,但我想知道使用shapely或sklearn.neighbors是否有更好或更快的方法或其他好处
import pandas as pd
import geopandas as gp
gdf1 > GeoDataFrame with point type geometry column - distance from this point
gdf2 > GeoDataFrame with point type geometry column - distance to this point
def knearest(from_points, to_points, k):
distlist = to_points.distance(from_points)
distlist.sort_values(ascending=True, inplace=True) # To have the closest ones first
return distlist[:k].mean()
# looping through a list of nearest points
for Ks in [1, 2, 3, 4, 5, 10]:
name = 'dist_to_closest_' + str(Ks) # to set column name
gdf1[name] = gdf1.geometry.apply(knearest, args=(gdf2, closest_x))
上面使用自动化GIS过程的答案非常好,但将点转换为numpy数组和弧度时会出现错误。纬度和经度是相反的
left_radians = np.array(left_gdf[left_geom_col].apply(lambda geom: (geom.y * np.pi / 180, geom.x * np.pi / 180)).to_list())
的确,点是用(纬度、经度)表示的,但经度对应于平面或球体的x轴,纬度对应于y轴
是的,但首先,我必须把赫尔辛基大学从automating GIS process,这里是the source code。下面是方法
首先,读取数据,例如,查找每栋建筑最近的公交车站
定义函数,在这里,您可以调整
k_neighbors
做最近邻分析
现在加入“从”和“到”数据帧
如果您的数据是在网格坐标中,那么这种方法会稍微精简一些,但只需一键即可
以sutan's answer为基础,精简赫尔辛基大学的街区
要获得多个邻居,您需要编辑k_neights参数……并且还必须在函数体中硬编码变量(请参见下面的“最近”和“最近距离”)并将它们添加到return语句中
因此,如果您想要两个最近的点,它看起来像:
输入是(x,y)元组的列表。因此,由于(通过问题标题)您的数据位于GeoDataframe中:
我对距离不感兴趣,因此我不在函数外添加注释,而是运行:
并获得两个长度相同的in_pts数组,分别包含qry_pts原始地理数据框中最近点和第二最近点的索引值
相关问题 更多 >
编程相关推荐