James Wong
James Wong

Reputation: 1137

How to calculate rolling means of second last week over a time series using Pandas

By second last week, I mean the values between last week today and the week before last week today.

For example, if today is Dec 13, I want to know the average value between Nov 29 and Dec 6. If today is Dec 14, I want to know the average value between Nov 30 and Dec 7. What's the proper way to achieve this in Python with Pandas?

Upvotes: 0

Views: 213

Answers (1)

rpanai
rpanai

Reputation: 13447

What about:

import pandas as pd
import numpy as np
N = 42
df = pd.DataFrame({"date":pd.date_range(start='2017-10-06',periods=N), "n":np.arange(N)})
df["roll"] = df["n"].shift(7).rolling(7).mean()

EDIT: You can check this for the dates you provide. Be care than from 2017-11-29 you go till 2017-12-05 included not 2017-12-06

Upvotes: 1

Related Questions