我正在努力计算多 组纬度和经度坐标之间的距离。简而言之,我找到了许多使用数学或 geopy 的教程。当我只想找到一组坐标(或两个唯一位置)之间的距离时,这些教程非常有用。但是,我的目标是扫描具有 400k 起点和终点坐标组合的数据集。下面列出了我使用的代码示例,但当我的数组大于 1 条记录时,我似乎遇到了错误。任何有用的提示将不胜感激。谢谢。
# starting dataframe is df
lat1 = df.lat1.as_matrix()
long1 = df.long1.as_matrix()
lat2 = df.lat2.as_matrix()
long2 = df.df_long2.as_matrix()
from geopy.distance import vincenty
point1 = (lat1, long1)
point2 = (lat2, long2)
print(vincenty(point1, point2).miles)
最佳答案
编辑:here's a simple notebook example
一种通用方法,假设您有一个包含点的 DataFrame 列,并且您想要计算所有点之间的距离(如果您有单独的列,首先将它们组合成 (lon, lat)
元组,例如)。将新列命名为 coords
.
import pandas as pd
import numpy as np
from geopy.distance import vincenty
# assumes your DataFrame is named df, and its lon and lat columns are named lon and lat. Adjust as needed.
df['coords'] = zip(df.lat, df.lon)
# first, let's create a square DataFrame (think of it as a matrix if you like)
square = pd.DataFrame(
np.zeros(len(df) ** 2).reshape(len(df), len(df)),
index=df.index, columns=df.index)
此函数从 df
中查找我们的“结束”坐标DataFrame 使用输入列名,然后应用 geopy vincenty()
对输入列中的每一行执行函数,使用 square.coords
列作为第一个参数。这是有效的,因为该函数从右到左按列应用。
def get_distance(col):
end = df.ix[col.name]['coords']
return df['coords'].apply(vincenty, args=(end,), ellipsoid='WGS-84')
现在我们已准备好计算所有距离。
我们正在转置 DataFrame ( .T
),因为 loc[]
我们将用来检索距离的方法是指索引标签、行标签。但是,我们的内部应用函数(见上文)用检索到的值填充一列
distances = square.apply(get_distance, axis=1).T
你的 geopy
值以公里为单位 (IIRC) 返回,因此您可能需要使用 .meters
将这些转换为您想要使用的任何单位, .miles
等等
像下面这样的东西应该可以工作:
def units(input_instance):
return input_instance.meters
distances_meters = distances.applymap(units)
您现在可以使用例如索引到距离矩阵中loc[row_index, column_index]
.
你应该能够很容易地适应上面的内容。您可能需要调整 apply
调用get_distance
函数以确保您将正确的值传递给 great_circle
. Pandas apply
文档可能很有用,特别是在使用 args
传递位置参数方面。 (你需要最新的 pandas 版本才能工作)。
此代码尚未分析,可能有更快的方法来执行此操作,但对于 400k 距离计算来说应该相当快。
哦还有
我不记得 geopy 是否期望坐标为 (lon, lat)
或 (lat, lon)
.我敢打赌是后者(叹气)。
更新 这是截至 2021 年 5 月的工作脚本。
import geopy.distance
# geopy DOES use latlon configuration
df['latlon'] = list(zip(df['lat'], df['lon']))
square = pd.DataFrame(
np.zeros((df.shape[0], df.shape[0])),
index=df.index, columns=df.index
)
# replacing distance.vicenty with distance.distance
def get_distance(col):
end = df.loc[col.name, 'latlon']
return df['latlon'].apply(geopy.distance.distance,
args=(end,),
ellipsoid='WGS-84'
)
distances = square.apply(get_distance, axis=1).T
关于python - 在python中计算*多*组地理坐标之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696613/