我正在尝试使用Haversine公式计算由纬度和经度标识的位置列表的距离矩阵,该公式需要两个坐标对的元组来生成距离:
def haversine(point1, point2, miles=False):
""" Calculate the great-circle distance bewteen two points on the Earth surface.
:input: two 2-tuples, containing the latitude and longitude of each point
in decimal degrees.
Example: haversine((45.7597, 4.8422), (48.8567, 2.3508))
:output: Returns the distance bewteen the two points.
The default unit is kilometers. Miles can be returned
if the ``miles`` parameter is set to True.
"""
我可以使用嵌套的for循环来计算所有点之间的距离,如下所示:
data.head()
id coordinates
0 1 (16.3457688674, 6.30354512503)
1 2 (12.494749307, 28.6263955635)
2 3 (27.794615136, 60.0324947881)
3 4 (44.4269923769, 110.114216113)
4 5 (-69.8540884125, 87.9468778773)
使用简单的函数:
distance = {}
def haver_loop(df):
for i, point1 in df.iterrows():
distance[i] = []
for j, point2 in df.iterrows():
distance[i].append(haversine(point1.coordinates, point2.coordinates))
return pd.DataFrame.from_dict(distance, orient='index')
但是,考虑到时间复杂度,对于500个数据点,这需要相当长的时间,大约需要20秒,而我的列表要长得多。因此我开始考虑矢量化,并且我发现了numpy.vectorize
(文档),但是我无法弄清如何在这种情况下使用它。