在数据框中计算纬度和经度之间的距离

6

我的数据框中有4列,包含以下数据:

Start_latitude<br>
Start_longitude<br>
Stop_latitude<br>
Stop_longitude<br>

我需要计算纬度和经度之间的距离,并创建一个新的列来存储所计算的距离。我找到了一个能够帮助我实现这一功能的包(geopy)。但是,我需要将一个元组传递给geopy。如何在pandas中对数据框中的所有记录应用此函数(geopy)?
2个回答

18

我建议您使用pyproj而不是geopy。geopy依赖于在线服务,而pyproj是本地的(这意味着它将更快,并且不依赖于互联网连接),并且对其方法更透明(例如,请参见此处),其基于Proj4代码库,该库是所有开源GIS软件以及您可能使用的许多Web服务的基础。

#!/usr/bin/env python3

import pandas as pd
import numpy as np
from pyproj import Geod

wgs84_geod = Geod(ellps='WGS84') #Distance will be measured on this ellipsoid - more accurate than a spherical method

#Get distance between pairs of lat-lon points
def Distance(lat1,lon1,lat2,lon2):
  az12,az21,dist = wgs84_geod.inv(lon1,lat1,lon2,lat2) #Yes, this order is correct
  return dist

#Create test data
lat1 = np.random.uniform(-90,90,100)
lon1 = np.random.uniform(-180,180,100)
lat2 = np.random.uniform(-90,90,100)
lon2 = np.random.uniform(-180,180,100)

#Package as a dataframe
df = pd.DataFrame({'lat1':lat1,'lon1':lon1,'lat2':lat2,'lon2':lon2})

#Add/update a column to the data frame with the distances (in metres)
df['dist'] = Distance(df['lat1'].tolist(),df['lon1'].tolist(),df['lat2'].tolist(),df['lon2'].tolist())

PyProj有一些文档在这里


问题在于我无法安装pyproj。我收到了安装失败的错误。它还要求我安装Visual Basic。 - Harikrishna
2
你是否正在使用anaconda?这是在Windows上尝试生存的更为明智的方式之一。 - Richard
它缺少Visual C++。成功安装了它。代码运行得很好!谢谢!只是好奇这是如何计算距离的?它在两点之间画一条直线吗? - Harikrishna
@Harikrishna:你所说的“直线”是什么意思?在欧几里得三维空间中,这将太短了。在球面上,大圆是最短距离;然而,地球是一个扁球体。Proj4使用的方法来自GeographicLib(请参见此处),使用WGS84椭球体,精度约为15纳米。我相信它基于C. F. F. Karney, Algorithms for gedesics, J. Geodesy ‘’‘87’‘’(1), 43-55 (2013), DOI: 10.1007/s00190-012-0578-z; geo-addenda.html. - Richard
@Harikrishna:如果您认为这个答案有帮助,请随意点击其左侧的上箭头进行点赞。如果您认为这是对您问题的最佳答案,您可以点击答案旁边的勾勾图标。 - Richard

5

从geopy的文档中得知:https://pypi.python.org/pypi/geopy。您可以通过以下方式来实现:

from geopy.distance import vincenty

# Define the two points
start = (start_latitute, start_longitude)
stop = (stop_latitude, stop_longitude)

# Print the vincenty distance
print(vincenty(start, stop).meters)

# Print the great circle distance
print(great_circle(start, stop).meters)

结合Pandas使用。假设您有一个数据框df。我们首先创建函数:

def distance_calc (row):
    start = (row['start_latitute'], row['start_longitude'])
    stop = (row['stop_latitude'], row['stop_longitude'])

    return vincenty(start, stop).meters

然后将其应用到数据帧:

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

注意axis=1指定符,这意味着应用是在行级别而不是列级别进行的。

如何在 Pandas 中对整个数据框应用操作? - Harikrishna
抱歉,我还在输入,我不小心点了提交。 - Remy Kabel
为什么会出现“DataFrame”对象没有“rows”属性的错误? - Harikrishna
谢谢!现在我遇到了这个问题。如果我使用 great_circle 找到距离,它可以工作。但是如果我使用 vincenty,它会说找不到 vincenty。 - Harikrishna
你是否正确导入了Vincenty?同时别忘了将问题标记为已回答。 - Remy Kabel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接