首页 > 解决方案 > 多列滚动窗口

问题描述

我面临以下问题:我需要根据高度和距离计算两点之间的斜率。

我使用 50 的滚动窗口,中心 = True。因此,对于某一行,斜率是根据 -25 个索引和 +25 个索引计算的。例如,如果 -25 (StartIndex) 处的高度为 80,+25 (EndIndex) 处的高度为 90,每行代表 10 米,那么斜率将是:(90-80)/500 = 0.02

但是,-25 和 +25 处的高度可能是 NaN 值。如果 NaN 值为 -25,StartIndex 将变为 -24(如果这也是 NaN,StartIndex 将变为 -23,等等)。EndIndex 也是如此。

现在我创建了以下函数并应用于滚动窗口。但是,只有高度从滚动窗口返回。

因此,我想知道如何在滚动窗口之后返回两列,以便使用 .apply(calculate_slope) 进行一些计算。

我创建了这个函数并应用了它。

def calculate_slope(df):
    df = df[df['Height'].notna()]

    StartIndex, EndIndex = df.iloc[0]['Height'], df.iloc[-1]['Height']
    first_KM, last_KM = df.iloc[0]['KM'], df.iloc[-1]['KM'] 

    slope = (EndIndex - StartIndex)/(last_KM - first_KM)  

    return slope
def get_slope(df, window_size=50):
    return df.assign(
        slope = lambda d: (d[['Height','KM']]
                             .rolling(window=window_size, center=True, min_periods=1)
                             .apply(calculate_slope, raw=False)
                            )
    )

这是示例数据框。

    KM        Height
0   0.25      NaN
1   0.5       2.0
2   0.75      3.0
3   1.0       NaN
4   1.25      5.0
5   1.5       6.0
6   1.75      7.0
7   2.0       8.0
8   2.25      NaN

因此,如果我们设置 window_size = 5,df.iloc[4] 的预期结果应该是:

斜率 = (7 - 3)/(1.75 - 0.75) = 4.0 其中 7 是df.iloc[-1]['Height'] 3 是df.iloc[0]['Height'] 1.75 是df.iloc[-1]['KM'] 0.75df.iloc[0]['Height']

但是,我立即收到错误,因为滚动窗口后的数据框不知道“高度”

KeyError: 'Height'

那么如何在应用时获得滚动后的“身高”和“公里”?

标签: pythonpandasnumpy

解决方案


推荐阅读