【发布时间】:2021-10-20 11:34:59
【问题描述】:
enter image description here我有一个带有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)
【问题讨论】:
-
您能否分享您数据框中的一些行以便我们进行测试?
-
我在描述中添加了一张图片:D @SergeBallesta
-
如果我正确理解您要做什么,我建议考虑以下两点:1. 使用
if (df.tripId[i] == x):而不是while(df.tripId[i]== x):2. 将结果保存到df.distance[i] -
我到底如何使用图像来提供数据帧???您能否将一些行共享为可复制的文本?
-
您能否为
coord1和coord2添加一些输入作为样本和预期结果以及创建的结果,以向我们展示它是如何不起作用的?
标签: python dataframe math jupyter-notebook data-analysis