gpt4 book ai didi

python - Scipy:如何将 KD-Tree 距离从查询转换为千米(Python/Pandas)

转载 作者:太空狗 更新时间:2023-10-30 02:55:16 24 4
gpt4 key购买 nike

这篇文章基于 this one .

我得到了一个 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}]);

对于每个城市,我试图找到另外两个最近的城市。因此我尝试了 scipy.spatial.KDTree。为此,我必须将大地坐标转换为 3D catesian 坐标(ECEF = earth-centered, earth-fixed):

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

给我这个:

python output

有了这个我可以创建 KDTree:

coordinates = list(zip(df['x'], df['y'], df['z']))

from scipy import spatial
tree = spatial.KDTree(coordinates)
tree.data

现在我正在柏林进行测试,

tree.query(coordinates[0], 2)

这正确地给出了柏林(本身)和波茨坦作为我列表中距离柏林最近的两个城市。

问题:但我想知道如何处理该查询的距离?它说 1501 - 但我如何将其转换为米或公里?柏林和波茨坦之间的实际距离是 27 公里,而不是 1501 公里。

备注:我知道我可以获得两个城市的经度/纬度并计算半正弦距离。但是使用 KDTree 的输出会很酷。

(array([ 0. , 1501.59637685]), array([0, 1]))

感谢任何帮助。

最佳答案

KDTree 正在计算两点(城市)之间的欧氏距离。两座城市和地心形成一个isosceles triangle .

德语维基百科条目包含对 geometric properties 的一个很好的概述。英文条目缺少。您可以使用它来计算距离。

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

更新

在关于获得相反的评论之后我重新阅读了这个问题并意识到虽然看起来可以使用上面提出的功能,但真正的问题在于其他地方。

to_Cartesian 函数中的

cossin 期望输入为 弧度 ( documentation )而您将角度交给他们。您可以使用上面定义的函数 deg2rad 将纬度和经度转换为弧度。这应该会直接为您提供与 KDTree 的距离(以公里为单位)。

关于python - Scipy:如何将 KD-Tree 距离从查询转换为千米(Python/Pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43020919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com