两列两行滚动的Pandas数据帧

2024-10-17 06:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个包含两个列的数据帧,它们保存着经纬度坐标:

将熊猫作为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的滚动。但一定有更简单的方法,对吧?在


Tags: 数据dataframedfpdvaluesrow1row2latitude
1条回答
网友
1楼 · 发布于 2024-10-17 06:32:15

Since pandas v0.23 it is now possible to pass a ^{} instead of a ^{} to Rolling.apply()。只需设置raw=False。在

raw : bool, default None

False : passes each row or column as a Series to the function.

True or None : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. The raw parameter is required and will show a FutureWarning if not passed. In the future raw will default to False.

New in version 0.23.0.

因此,在给定示例的基础上,可以将纬度移动到索引,并将整个经度系列(包括索引)传递给函数:

df = df.set_index('Latitude')
df['Distance'] = df['Longitude'].rolling(2).apply(haversine_distance, raw=False)

相关问题 更多 >