如何使用 geopanda 或 shapely 在同一地理数据框中找到最近的点

rzt*_*101 3 python gis shapely geopandas

我有一个显示约 25 个位置的地理数据框,表示为点几何。我试图想出一个脚本,通过每个点,标识最近的位置并返回最近位置的名称和距离。

如果我使用 shapely.ops 库中的nearest_points(geom1, geom2) 有不同的地理数据框,我可以轻松地做到这一点。然而,我所有的位置都存储在一个地理数据框中。我正在尝试循环,这就是我遇到麻烦的地方

这是我的示例文件:

geofile=gpd.GeoDataFrame([[0,'location A',Point(55,55)],[1,'location B',Point(66,66)],[2, 'Location C' ,Point(99,99)],[3, 'Location D' ,Point(11,11)]],columns=['ID','Location','geometry'])
Run Code Online (Sandbox Code Playgroud)

这是我创建的循环无济于事。

for index, row in geofile.iterrows():
    nearest_geoms=nearest_points(row, geofile)
    print('location:' + nearest_geoms[0])
    print('nearest:' + nearest_geoms[1])
    print('-------')
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

AttributeError: 'Series' object has no attribute '_geom'
Run Code Online (Sandbox Code Playgroud)

但是我认为我的问题超出了错误原因我必须排除我正在循环的行,因为它是那个位置,它将自动返回为最近的位置。

我对一个位置的最终结果如下:

([0,'location A','location B', '5 miles', Point(55,55)], columns=['ID','Location','Nearest', 'Distance',geometry'])
Run Code Online (Sandbox Code Playgroud)

Chr*_*eke 9

Shapely 的nearest_points 函数比较匀称的几何形状。要将单个 Point 几何与多个其他 Point 几何进行比较,您可以使用 .unary_union 与生成的 MultiPoint 几何进行比较。是的,在每一行操作中,删除相应的点,这样它就不会与自身进行比较。

import geopandas as gpd
from shapely.geometry import Point
from shapely.ops import nearest_points

df = gpd.GeoDataFrame([[0, 'location A', Point(55,55)], 
                       [1, 'location B', Point(66,66)],
                       [2, 'Location C', Point(99,99)],
                       [3, 'Location D' ,Point(11,11)]], 
                      columns=['ID','Location','geometry'])
df.insert(3, 'nearest_geometry', None)

for index, row in df.iterrows():
    point = row.geometry
    multipoint = df.drop(index, axis=0).geometry.unary_union
    queried_geom, nearest_geom = nearest_points(point, multipoint)
    df.loc[index, 'nearest_geometry'] = nearest_geom
Run Code Online (Sandbox Code Playgroud)

导致

    ID  Location    geometry        nearest_geometry
0   0   location A  POINT (55 55)   POINT (66 66)
1   1   location B  POINT (66 66)   POINT (55 55)
2   2   Location C  POINT (99 99)   POINT (66 66)
3   3   Location D  POINT (11 11)   POINT (55 55)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明