使用谷歌地图 API 计算熊猫数据帧中经纬度之间的距离

Posted

技术标签:

【中文标题】使用谷歌地图 API 计算熊猫数据帧中经纬度之间的距离【英文标题】:Use google maps API to calculate distance between lat-longs in a pandas dataframe 【发布时间】:2021-03-17 07:49:20 【问题描述】:

我有一个 pandas 数据框,它的 sn-p 如下所示:

test
latitude   longitude
17.355282  99.149210
17.355282  99.149210
17.355377  99.149220
17.355377  99.149220
17.355300  99.149280
17.355389  99.149254

我希望有一个新列,比如“距离”,它使用 python 中的 googlemaps API 计算每个连续条目之间的距离。

我写了一个这样的函数:

def calculate_distance(lat1, lon1, lat2, lon2):

    distance = gmaps.distance_matrix([str(lat1) + " " + str(lon1)], 
                                 [str(lat2) + " " + str(lon2)], 
                                 mode='walking')['rows'][0]['elements'][0]['distance']['text'].split(' ')[0]
    return distance

当我调用这个函数时:

calculate_distance(test.latitude.values, test.longitude.values,
                 test.loc[1:, 'latitude'].values, test.loc[1:, 'longitude'].values)

我收到以下回复:

'status': 'NOT_FOUND'

在调用函数时,我还在我的第一个 lat-long 中添加了一个 shift 函数,如下所示:

calculate_distance(test.latitude.shift(), test.longitude.shift(),
                 test.loc[1:, 'latitude'].values, test.loc[1:, 'longitude'].values)

它将nan 值放在第一个条目中,并给出以下 KeyError:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-199-8da29743b4a6> in <module>
      1 calculate_distance(test.latitude.shift(), test.longitude.shift(),
----> 2                  test.loc[1:, 'latitude'].values, test.loc[1:, 'longitude'].values)

<ipython-input-198-64f14b39eec4> in calculate_distance(lat1, lon1, lat2, lon2)
     11     distance = gmaps.distance_matrix([str(lat1) + " " + str(lon1)], 
     12                                  [str(lat2) + " " + str(lon2)],
---> 13                                  mode='walking')['rows'][0]['elements'][0]['distance']['text'].split(' ')[0]
     14     return distance
     15 

KeyError: 'distance'

我验证了 AP​​I,它使用前两个 lat long 工作:

distance = gmaps.distance_matrix([str(17.355282) + " " + str(99.14921)], 
                                 [str(17.355282) + " " + str(99.149210)], 
                                 mode='walking')['rows'][0]['elements'][0]['distance']['text']

distance
'1 m'

这里出了什么问题?感谢任何帮助。

谢谢

【问题讨论】:

【参考方案1】:

通过DataFrame.shift新建列,然后调用DataFrame.apply中的函数,不漏值:

test[['lat_shifted','long_shifted']] = test[['latitude','longitude']].shift(-1)


f = lambda x: calculate_distance(x['lat_shifted'], x['long_shifted'], x['latitude'], x['longitude'])
test['new'] = test.dropna().apply(f, axis = 1)

【讨论】:

以上是关于使用谷歌地图 API 计算熊猫数据帧中经纬度之间的距离的主要内容,如果未能解决你的问题,请参考以下文章

如何使用经纬度坐标计算谷歌地图上两条路径线之间的角度

使用谷歌地图v3验证两点(纬度或地址)服务器端之间的路线距离

[转]层行列和经纬度坐标之间的相互转化方法(谷歌地图)

获取经纬度之间的项目

如何在没有谷歌地图 API 的情况下在我的应用程序中获取经度和纬度?

在iphone中使用谷歌地图计算两个位置之间的距离