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)