如何使用pandas数据帧中的纬度和经度计算距离?

问题描述 投票:0回答:2

我的数据框有两列纬度和经度,以及863行,因此每行都有一个由纬度和经度定义的点坐标。现在我想计算以千米为单位的所有行之间的距离。我使用以下参考链接来获取纬度和经度对之间的距离。如果有几行,我可以使用引用链接。但我有大行,我想我需要一个循环来实现问题的解决方案。由于我是python的新手,我无法创建一个循环这个想法的逻辑。

参考链接:Getting distance between two points based on latitude/longitude

我的数据框如下所示:

read_randomly_generated_lat_lon.head(3)
Lat          Lon
43.937845   -97.905537
44.310739   -97.588820
44.914698   -99.003517
python-3.x pandas geolocation latitude-longitude
2个回答
3
投票

请注意:以下脚本不考虑地球的曲率。有很多文件Convert lat/long to XY解释这个问题。

但是,可以粗略地确定坐标之间的距离。出口是一个系列,可以很容易concatenated与你原来的df提供一个单独的column显示相对于你的坐标距离。

d = ({
    'Lat' : [43.937845,44.310739,44.914698],       
    'Long' : [-97.905537,-97.588820,-99.003517],                               
     })

df = pd.DataFrame(d)

df = df[['Lat','Long']]

point1 = df.iloc[0]

def to_xy(point):

    r = 6371000 #radians of the earth (m)
    lam,phi = point
    cos_phi_0 = np.cos(np.radians(phi))

    return (r * np.radians(lam) * cos_phi_0, 
            r * np.radians(phi))

point1_xy = to_xy(point1)

df['to_xy'] = df.apply(lambda x: 
         tuple(x.values),
         axis=1).map(to_xy)

df['Y'], df['X'] = df.to_xy.str[0], df.to_xy.str[1]

df = df[['X','Y']] 
df = df.diff()

dist = np.sqrt(df['X']**2 + df['Y']**2)

#Convert to km
dist = dist/1000

print(dist)

0           NaN
1     41.149537
2    204.640462

2
投票

你可以使用scikit-learn来做到这一点:

import numpy as np
from sklearn.neighbors import DistanceMetric

dfr = df.copy()
dfr.Lat = np.radians(df.Lat)
dfr.Lon = np.radians(df.Lon)
hs = DistanceMetric.get_metric("haversine")
(hs.pairwise(dfr)*6371) # Earth radius in km

输出:

array([[  0.        ,  48.56264446, 139.2836099 ],
       [ 48.56264446,   0.        , 130.57312786],
       [139.2836099 , 130.57312786,   0.        ]])

注意,输出是方阵,其中元素(i,j)是第i行和第j行之间的距离

这似乎比使用scipy的pdist和自定义haversine函数更快

© www.soinside.com 2019 - 2024. All rights reserved.