Mat*_*ias 5 python spatial geospatial kdtree scipy
这篇文章建立在这篇文章的基础上。
我得到了一个 Pandas 数据框,其中包含城市的地理坐标(大地坐标)作为经度和纬度。
import pandas as pd
df = pd.DataFrame([{'city':"Berlin", 'lat':52.5243700, 'lng':13.4105300},
{'city':"Potsdam", 'lat':52.3988600, 'lng':13.0656600},
{'city':"Hamburg", 'lat':53.5753200, 'lng':10.0153400}]);
Run Code Online (Sandbox Code Playgroud)
对于每个城市,我都试图找到最近的另外两个城市。因此我尝试了 scipy.spatial.KDTree。为此,我必须将大地坐标转换为 3D 笛卡尔坐标(ECEF = 以地球为中心、以地球固定):
from math import *
def to_Cartesian(lat, lng):
R = 6367 # radius of the Earth in kilometers
x = R * cos(lat) * cos(lng)
y = R * cos(lat) * sin(lng)
z = R * sin(lat)
return x, y, z
df['x'], df['y'], df['z'] = zip(*map(to_Cartesian, df['lat'], df['lng']))
df
Run Code Online (Sandbox Code Playgroud)
这给我这个:
这样我就可以创建 KDTree:
coordinates = list(zip(df['x'], df['y'], df['z']))
from scipy import spatial
tree = spatial.KDTree(coordinates)
tree.data
Run Code Online (Sandbox Code Playgroud)
现在我正在柏林测试它,
tree.query(coordinates[0], 2)
Run Code Online (Sandbox Code Playgroud)
这正确地将柏林(本身)和波茨坦作为我的列表中距离柏林最近的两个城市。
问题:但我想知道如何处理与该查询的距离?它显示 1501 - 但我如何将其转换为米或公里?柏林和波茨坦之间的实际距离是 27 公里,而不是 1501 公里。
备注:我知道我可以获得两个城市的经度/纬度并计算半正矢距离。但使用 KDTree 的输出来代替会很酷。
(数组([ 0., 1501.59637685]), 数组([0, 1]))
任何帮助表示赞赏。
KDTree 正在计算两点(城市)之间的欧氏距离。两座城市与地心构成一个等腰三角形。
德语维基百科条目包含了英语条目所缺乏的几何属性的良好概述。您可以使用它来计算距离。
import numpy as np
def deg2rad(degree):
rad = degree * 2*np.pi / 360
return(rad)
def distToKM(x):
R = 6367 # earth radius
gamma = 2*np.arcsin(deg2rad(x/(2*R))) # compute the angle of the isosceles triangle
dist = 2*R*sin(gamma/2) # compute the side of the triangle
return(dist)
distToKM(1501.59637685)
# 26.207800812050056
Run Code Online (Sandbox Code Playgroud)
在获得相反的评论后,我重新阅读了这个问题,并意识到虽然似乎可以使用上面提出的函数,但真正的问题在于其他地方。
cos并且sin在您的函数中to_Cartesian期望输入位于radians(文档)中,而您以度为单位传递角度。您可以使用上面定义的函数deg2rad将纬度和经度转换为弧度。这将为您提供直接距 KDTree 的距离(以公里为单位)。