简体   繁体   中英

How to create a rolling window of fixed length in pandas?

Given a timeseries, how do I create a rolling window of some interval such that it starts with that same interval, instead of expanding from size 1. As seen here:

import pandas as pd
from datetime import timedelta

# 'per' x 1 minute (1T) intervals 
per = 10
d = pd.DataFrame(
    {'a': list(range(per))}, 
    index=pd.date_range('2021-05-01T0000', freq='1T', periods=per))

# create a rolling 5 minute window and get its length
w = d.rolling(timedelta(minutes=5))
for wi in w:
    print(len(wi))

# Output (window lengths):
# Window starts with length 1 and iterates until it expands
# to desired size:
#1
#2
#3
#4
#5  < I only want windows starting here
#5
#5
#5
#5

How to instead start the window with the specified window size?

Maybe a "workaround": you can use itertools.dropwhile to filter the windows with length < 5:

from itertools import dropwhile

w = dropwhile(lambda w: len(w) < 5, d.rolling(timedelta(minutes=5)))
for wi in w:
    print(len(wi))

Prints:

5
5
5
5
5
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM