Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scipy:如何将KD树距离从查询转换为公里(Python/Pandas)_Python_Scipy_Geospatial_Spatial_Kdtree - Fatal编程技术网

Scipy:如何将KD树距离从查询转换为公里(Python/Pandas)

Scipy:如何将KD树距离从查询转换为公里(Python/Pandas),python,scipy,geospatial,spatial,kdtree,Python,Scipy,Geospatial,Spatial,Kdtree,这篇文章的基础是 我得到了一个熊猫数据框,其中包含城市的地理坐标(大地坐标)为经度和纬度 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

这篇文章的基础是

我得到了一个熊猫数据框,其中包含城市的地理坐标(大地坐标)为经度和纬度

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。为此,我必须将大地坐标转换为三维悬链线坐标(ECEF=地球中心,地球固定):

给我这个:

通过此操作,我可以创建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的输出会很酷

(数组([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

更新 在关于获得相反结果的评论之后,我重新阅读了这个问题,并意识到,虽然人们似乎可以使用上面提出的函数,但真正的问题在于其他地方


cos
sin
函数中的
to_Cartesian
期望输入为
弧度
(),而您将角度以度为单位传递给它们。您可以使用上面定义的函数
deg2rad
将纬度和经度转换为弧度。这应该给出直接从KDTree到KDTree的距离(以km为单位)。

您能给出相反的距离吗?将400米转换为欧几里得距离?@Matthias我更新了我的答案。现在我对它进行了更深入的思考,我不确定为什么这两个向量(分别从地球中心到两个城市)之间的角度看起来是守恒的,尽管转换函数中使用的是度而不是弧度。很抱歉我没早点发现。太好了,谢谢你的提示。没错,现在从KD树返回的距离也很好。如果使用数学包(来自math import radians)@Niklas中的弧度函数,则不需要deg2rad函数。。。此函数仅返回转换为弧度的输入,仅此而已!(因此它与np.deg2rad(x)相同)
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