使用Pandas和Geopy计算两组纬度/经度坐标之间的距离

时间:2019-12-16 22:30:16

标签: python pandas geopy

我正在尝试使用2个不同的数据帧,每个数据帧具有一组不同的纬度/经度坐标,以使用Geopy计算它们之间的距离。

from geopy import distance

def dist_calc (row):
    start = (row['Lat_1' ], row['Long_1'])
    stop = (row['Lat_2'], row['Long_2'])
    return distance.great_circle(start, stop).km

df['distance'] = df.apply (lambda row: dist_calc (row), axis=1)

我一直收到以下错误。 我也尝试过使用ignore_index = True。

KeyError: ('Lat_2', 'occurred at index 0')

我是否需要合并或连接我的数据框以完成此操作?或者如何使此代码起作用?

1 个答案:

答案 0 :(得分:0)

连接您的dfs,然后运行您的函数:

new_df = pd.concat([df1, df2], axis=1)

def dist_calc (row):
    start = (row['Lat_1' ], row['Long_1'])
    stop = (row['Lat_2'], row['Long_2'])
    return distance.great_circle(start, stop).km

new_df['distance'] = new_df.apply (lambda row: dist_calc (row), axis=1)