我得到了一个包含两个列的数据帧,它们保存着经纬度坐标:
将熊猫作为pd导入
values = {'Latitude': {0: 47.021503365600005,
1: 47.021503365600005,
2: 47.021503365600005,
3: 47.021503365600005,
4: 47.021503365600005,
5: 47.021503365600005},
'Longitude': {0: 15.481974060399999,
1: 15.481974060399999,
2: 15.481974060399999,
3: 15.481974060399999,
4: 15.481974060399999,
5: 15.481974060399999}}
df = pd.DataFrame(values)
df.head()
现在我想在dataframe上应用一个滚动窗口函数,它获取一行和另一行的经度和纬度(两列)(窗口大小2),以便计算haversine距离。在
^{pr2}$我的问题是我从来没有得到所有四个值Lng1,Lat1(第一行)和Lng2,Lat2(第二行)。如果我使用axis=1,那么我将得到第一行的Lng1和Lat1。如果我使用axis=0,那么我将得到第一行和第二行的Lng1和Lng2,但是只有经度。在
如何应用使用两行两列的滚动窗口?有点像这样:
def haversine_distance(x):
row1 = x[0]
row2 = x[1]
lng1, lat1 = row1['Longitude'], row1['Latitude']
lng2, lat2 = row2['Longitude'], row2['Latitude']
# do your stuff here
return 1
目前,我正在通过shift(-1)将dataframe与其自身连接起来,从而在一行中生成所有四个坐标。但滚动也是可能的。另一个选择是将Lng和Lat组合成一个列,并在其上应用轴=0的滚动。但一定有更简单的方法,对吧?在
Since pandas v0.23 it is now possible to pass a ^{} instead of a ^{} to Rolling.apply() 。只需设置
raw=False
。在因此,在给定示例的基础上,可以将纬度移动到索引,并将整个经度系列(包括索引)传递给函数:
相关问题 更多 >
编程相关推荐