简体   繁体   中英

Add rolling window to columns in each row in pandas

I have a timeseries in a dataframe and would like to add the rolling window with window size n to each of the rows.

df['A'].rolling(window=6)

This mean each row would have additional 6 columns with the respective numbers of the rolling window of that column. How can I achieve this using the rolling function of pandas, automatically naming the columns [t-1, t-2, t-3...tn]?

df.shift(n) is what you're looking for:

n = 6 # max t-n
for t in range(1, n+1):
    df[f'A-{t}'] = df['A'].shift(t)

Ref. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html

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