问题描述
这是一个非常简单的案例,但是到目前为止,我还没有找到任何简单的方法来做到这一点。想法是获得GeoDataFrame
中定义的所有点与另一个GeoDataFrame
中定义的点之间的距离。
import geopandas as gpd
import pandas as pd
# random coordinates
gdf_1 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0,0],[0,90,120]))
gdf_2 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0,-90]))
print(gdf_1)
print(gdf_2)
# distances are calculated elementwise
print(gdf_1.distance(gdf_2))
这将产生gdf_1
和gdf_2
中共享相同索引的点之间的元素方向距离(并发出警告,因为两个GeoSeries没有相同的索引,这就是我的情况) )。
geometry
0 POINT (0.000 0.000)
1 POINT (0.000 90.000)
2 POINT (0.000 120.000)
geometry
0 POINT (0.00000 0.00000)
1 POINT (0.00000 -90.00000)
/home/seydoux/anaconda3/envs/chelyabinsk/lib/python3.8/site-packages/geopandas/base.py:39: UserWarning: The indices of the two GeoSeries are different.
warn("The indices of the two GeoSeries are different.")
0 0.0
1 180.0
2 NaN
问题是;如何获得一系列所有点到点的距离(或者至少gdf_1
和gdf_2
的索引是对称的,因此是唯一的组合)。
编辑
-
在this post中,仅提出了按元素的操作。
-
还提出了一个类似的问题on the GitHub repo of geopandas。提出的解决方案之一是使用
apply
方法,而没有任何详细的答案。
解决方法
您必须在第一个gdf中的每个几何体上应用以获取到第二个gdf中的所有几何体的距离。
import geopandas as gpd
import pandas as pd
# random coordinates
gdf_1 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0,0],[0,90,120]))
gdf_2 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0,-90]))
gdf_1.geometry.apply(lambda g: gdf_2.distance(g))
0 1
0 0.0 90.0
1 90.0 180.0
2 120.0 210.0