多列滚动窗口

2024-04-19 13:02:39 发布

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

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

我使用50的滚动窗口,中心=真。所以对于某一行,斜率是基于-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\u 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

因此,如果我们将窗口大小设置为5,则测向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.75 df.iloc[0]['Height']

但是,我立即得到一个错误,因为滚动窗口后的数据帧不知道“Height”

KeyError: 'Height'

那么,在申请时,如何获得滚压后的“高度”和“公里”?你知道吗


Tags: 函数df高度nan指数windowslopeapply