Mat*_*ias 5 python pandas rolling-computation
我有一个包含两列的数据框,其中包含经度和纬度坐标:
将熊猫作为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()
Run Code Online (Sandbox Code Playgroud)
现在,我想在数据框上应用滚动窗口函数,该函数采用一行和另一行(窗口大小为2)的经度和纬度(两列)来计算hasrsine距离。
def haversine_distance(x):
print (x)
df.rolling(2, axis=1).apply(haversine_distance)
Run Code Online (Sandbox Code Playgroud)
我的问题是,我从未获得全部四个值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
Run Code Online (Sandbox Code Playgroud)
目前,我正在通过shift(-1)将数据框与其自身连接在一起,从而在一行中生成所有四个坐标,从而进行此计算。但是滚动也应该是可能的。另一种选择是将Lng和Lat合并为一列,并在其上应用axis = 0的滚动。但是必须有一种更简单的方法,对吗?
从 pandas v0.23 开始,现在可以将 aSeries而不是 a传递ndarray给 Rolling.apply()。刚设置raw=False。
raw : bool, 默认无
False: 将每一行或每一列作为一个系列传递给函数。
True或None:传递的函数将接收 ndarray 对象。如果您只是应用 NumPy 缩减功能,这将获得更好的性能。原始参数是必需的,如果未通过,将显示 FutureWarning。将来 raw 将默认为 False。0.23.0 版中的新功能。
因此,以您给定的示例为基础,您可以将纬度移动到索引并将整个经度系列(包括索引)传递给您的函数:
df = df.set_index('Latitude')
df['Distance'] = df['Longitude'].rolling(2).apply(haversine_distance, raw=False)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1911 次 |
| 最近记录: |