Reputation: 6587
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
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