Returns the average rental value for the number of periods specified by the window parameter. For instance. window = 1 will return the original list. Window = 2 will calculate the average over 2 days and so on.
index=pd.date_range(start="4th of July 2017",periods=30,freq="D") df=pd.DataFrame(np.random.randint(0,100,30),index=index) print([pd.rolling_mean(df,window=i,freq="D") for i in range(1,5)])
.....
2017-07-04 NaN 2017-07-05 20.5 2017-07-06 64.5 2017-07-07 58.5 2017-07-08 13.0 2017-07-09 4.5 2017-07-10 17.5 2017-07-11 23.5 2017-07-12 40.5 2017-07-13 60.0 2017-07-14 73.0 2017-07-15 90.0 2017-07-16 56.5 2017-07-17 55.0 2017-07-18 57.0 2017-07-19 45.0 2017-07-20 77.0 2017-07-21 46.5 2017-07-22 3.5 2017-07-23 48.5 2017-07-24 71.5 2017-07-25 52.0 2017-07-26 56.5 2017-07-27 47.5 2017-07-28 64.0 2017-07-29 82.0 2017-07-30 68.0 2017-07-31 72.5 2017-08-01 58.5 2017-08-02 67.0
.....
Next, you can reset the NA values โโusing the df dropna method, for example:
df.rolling(window=2,freq="D").mean().dropna()
So, all the code that should print you a moving average for months:
print([df.rolling(i,freq="m").mean().dropna() for i in range(len(df.rolling(window=1,freq="m").sum()))])
source share