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

Calculate distance between latitude and longitude in dataframe

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

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

我需要计算纬度经度对之间的距离,并创建一个包含计算距离的新列。

我遇到了一个可以为我做这件事的包 (geopy)。但是我需要将一个元组传递给 geopy。我如何在 pandas 中的数据框中为所有记录应用此函数 (geopy)?

来自 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 说明符,这意味着应用程序是在行级别而不是列级别完成的。

我建议您使用 pyproj 而不是 geopy。 geopy 依赖于在线服务,而 pyproj 是本地的(这意味着它会更快并且不依赖互联网连接)并且其方法更加透明(例如参见 [​​=11=]),它们基于 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 有一些文档 here