Nickpick
Nickpick

Reputation: 6587

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...t-n]?

Upvotes: 0

Views: 475

Answers (1)

Georgina Skibinski
Georgina Skibinski

Reputation: 13377

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

Upvotes: 1

Related Questions