其他分享
首页 > 其他分享> > pandas滑动窗口滑动整个dataframe

pandas滑动窗口滑动整个dataframe

作者:互联网

pandas rolling官方文档:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html

使用rolling会导致dataframe中每一列都单独执行,但是在某些情况下希望整个dataframe顺溜的从上到下依次返回,所以使用一个功能方法:

def rolling_dataframe(dataframe: pd.DataFrame, window: int):
    """
    将整个dataframe作为一个整体进行滑动
    :param dataframe:
    :param window:
    :return:
    """
    for i in range(dataframe.shape[0] - window):
        yield dataframe.iloc[i:i + window]

示例代码

import pandas as pd
import numpy as np


def rolling_dataframe(dataframe: pd.DataFrame, window: int):
    """
    将整个dataframe作为一个整体进行滑动
    :param dataframe:
    :param window:
    :return:
    """
    for i in range(dataframe.shape[0] - window):
        yield dataframe.iloc[i:i + window]


if __name__ == '__main__':
    df = pd.DataFrame(np.random.random(size=(10, 4)))
    for sub_df in rolling_dataframe(df, 3):
        print(sub_df)

标签:__,dataframe,window,param,rolling,滑动,pandas
来源: https://blog.csdn.net/weixin_35757704/article/details/122328532