我没有使用scipy
的pdist
函数的结果。我对真实的地理距离感兴趣(首选单位:km)。采取以下坐标:
from scipy.spatial.distance import pdist
coordinates = [ (42.057, -71.08), (39.132, -84.5155) ]
distance = pdist(coordinates)
print distance
# [ 13.75021037]
但是这个单位是什么?谷歌表示,这两点之间的距离是1179公里。我如何从13.75021037到达那里?
使用最新的Python 3,现在提供了弃用警告。我实际上发现this answer的@cffk更容易理解:
(为方便起见,这里粘贴)
>>> from geopy.distance import great_circle
>>> from geopy.distance import geodesic
>>> p1 = (31.8300167,35.0662833) # (lat, lon) - https://goo.gl/maps/TQwDd
>>> p2 = (31.8300000,35.0708167) # (lat, lon) - https://goo.gl/maps/lHrrg
>>> geodesic(p1, p2).meters
429.1676644986777
>>> great_circle(p1, p2).meters
428.28877358686776
来自pdist
的scipy
方法不支持lon
,lat
坐标的距离,如评论中所述。
但是,如果你想获得pdist
返回的那种距离矩阵,你可以使用pdist
方法和geopy
包中提供的距离方法。为此,pdist
允许使用具有两个参数(lambda函数)的自定义函数计算距离。
这是一个例子:
from scipy.spatial.distance import pdist
from geopy.distance import vincenty
import numpy as np
coordinates = np.array([[19.41133431, -99.17822823],
[19.434514 , -99.180934],
[19.380412 , -99.178789])
# Using the vincenty distance function.
m_dist = pdist(coordinates, # Coordinates matrix or tuples list
# Vicenty distance in lambda function
lambda u, v: vincenty(u, v).kilometers)