在获得两个坐标之间的距离时出错

时间:2018-05-18 00:31:33

标签: python pandas dataframe distance haversine

我有panda dataframe以下schema

customer_id                                     int64
vehicle_type                                   object
pickup_place                                   object
place_category                                 object
how_long_it_took_to_order                      object
pickup_lat                                    float64
pickup_lon                                    float64
dropoff_lat                                   float64
dropoff_lon                                   float64
pickup_coord                                   object
dropoff_coord                                  object
dtype: object

我试图找到拾取和放下位置之间的距离。所以我最初尝试通过hasrsine公式使用Getting distance between two points based on latitude/longitude方法。当我尝试使用

将度数转换为弧度时
df_post['lat1'] = radians(df_post['pickup_lat'])

我收到了这个错误:

TypeError: cannot convert the series to <class 'float'>

所以我尝试在第3个回复中使用geopy.distance模块使用内置函数,并为此创建了lat和long的元组。

df_post['pickup_coord']=list(zip(df_post['pickup_lat'],df_post['pickup_lon']))
df_post['dropoff_coord']=list(zip(df_post['dropoff_lat'],df_post['dropoff_lon'])

但是当我尝试内置功能时

df_post['pickup_dropoff_distance']=gd.VincentyDistance(df_post['pickup_coord'],df_post['dropoff_coord']).miles

我收到一个新错误:

ValueError: When creating a Point from sequence, it must not have more than 3 items.

有人可以帮助我解决为什么会出现错误,以及可能的解决方案。

2 个答案:

答案 0 :(得分:1)

距离计算器的语法为geopy.distance.VincentyDistance(coords_1, coords_2).miles,其中coords_1coords_2为元组。

要将函数应用于数据框中的每一行,您需要使用pd.DataFrame.apply

def distancer(row):
    coords_1 = (row['pickup_lat'], row['pickup_long'])
    coords_2 = (row['dropoff_lat'], row['dropoff_long'])
    return geopy.distance.VincentyDistance(coords_1, coords_2).miles

df_post['pickup_dropoff_distance'] = df_post.apply(distancer, axis=1)

答案 1 :(得分:-2)

试试这个应该有效

df_post['lat1'] = radians(df_post['pickup_lat'].astype(float))