【问题标题】:Use google maps API to calculate distance between lat-longs in a pandas dataframe使用谷歌地图 API 计算熊猫数据帧中经纬度之间的距离
【发布时间】: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'

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

谢谢

【问题讨论】:

    标签: python pandas google-maps


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-03
      • 2011-05-18
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2014-05-01
      • 2019-08-23
      • 1970-01-01
      相关资源
      最近更新 更多