python - 2个gps坐标之间的距离
问题描述
在此处输入图像描述我有一个带有gps数据(经度和纬度)和tripId的数据框,我想计算每个tripId的每个gps坐标(每一行)之间的距离,是否可以添加一个新列“距离”,其中包含结果(我会有 sum(row)-1 )?
- timestamp longitude latitude tripId
0 2021-04-30 21:13:53 8.211610 53.189479 1790767
1 2021-04-30 21:13:54 8.211462 53.189479 1790767
2 2021-04-30 21:13:55 8.211367 53.189476 1790767
3 2021-04-30 21:13:56 8.211343 53.189479 1790767
4 2021-04-30 21:13:57 8.211335 53.189490 1790767
5 2021-04-30 21:13:59 8.211338 53.189491 1790767
6 2021-04-30 21:14:00 8.211299 53.189479 1790767
7 2021-04-30 21:14:01 8.211311 53.189468 1790767
8 2021-04-30 21:14:02 8.211327 53.189446 1790767
9 2021-04-30 21:14:03 8.211338 53.189430 1790767
我已经测试了前 10 行,但仍然无法正常工作
import math
def haversine(coord1, coord2):
R = 6372800 # Earth radius in meters
lat1, lon1 = coord1
lat2, lon2 = coord2
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = math.sin(dphi/2)**2 + \
math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2
return 2*R*math.atan2(math.sqrt(a), math.sqrt(1 - a))
x= df.tripId[0]
for i in range(0,10):
while(df.tripId[i]== x):
coord1= df.latitude[i], df.longitude[i]
coord2= df.latitude[i+1], df.longitude[i+1]
df.distance=haversine(coord1, coord2)
解决方案
hasrsine 模块已经包含一个可以直接处理向量的函数。由于您的输入数据已经是一个数据框,您应该使用haversine_vector
. 即使您的数据帧包含多个 idTrip 值,您也可以使用它直接计算距离列:
def calc_dist(df):
s = pd.Series(haversine.haversine_vector(df, df.shift()),
index=df.index, name='distance')
return pd.DataFrame(s)
df = pd.concat([df, df.groupby('idTrip')[['latitude', 'longitude']].apply(calc_dist)],
axis=1)
根据您的样本数据,它给出:
- timestamp longitude latitude tripId distance
0 2021-04-30 21:13:53 8.211610 53.189479 1790767 NaN
1 2021-04-30 21:13:54 8.211462 53.189479 1790767 0.009860
2 2021-04-30 21:13:55 8.211367 53.189476 1790767 0.006338
3 2021-04-30 21:13:56 8.211343 53.189479 1790767 0.001633
4 2021-04-30 21:13:57 8.211335 53.189490 1790767 0.001334
5 2021-04-30 21:13:59 8.211338 53.189491 1790767 0.000229
6 2021-04-30 21:14:00 8.211299 53.189479 1790767 0.002921
7 2021-04-30 21:14:01 8.211311 53.189468 1790767 0.001461
8 2021-04-30 21:14:02 8.211327 53.189446 1790767 0.002668
9 2021-04-30 21:14:03 8.211338 53.189430 1790767 0.001924
推荐阅读
- python - wordpress 可以用作 python bot 的前端吗?
- javascript - Node.js 在接收 SIGTERM 时的默认行为是什么?
- python - hub.get_expected_image_size 生成错误
- python - 销毁按钮 Tkinter 的问题,NameError
- javascript - calculating max - min within for loop
- javascript - 如何在 React 的 onLoad 中放置多个 If 语句
- json - Ansible:如何在 json_query 中使用一些分隔符拆分 json 数据
- c++ - 如何在 C++ 中准确地显示、存储和使用精确到一定小数位数的数据?
- php - 创建函数以显示单个产品的图像或占位符图像
- javascript - JS Map 仅显示最后一个结果