While doing statical analysis on any dataset we need to calculate various statical measure in various form. Have you ever tried to calculate any measure for a specific numbers of rows and then moving to another set of row by increasing the index value of every row by one. It will give us the statical measure for every set of data and by this we can get the idea that how the measure is changing with the rows. This can be done by rolling function.
This python source code does the following :
1. Creates your own time series data.
2. Adding new columns to datagram
3. Finds mean and max for rolling window
So this is the recipe on how we can deal with Rolling Time Window in Python.
import pandas as pd
We have only imported Pandas which is needed.
We have created an array of date by using the function date_range in which we have passed the initial date, period and the frequency as weekly. Then we have passed it through pd.DataFrame as a index to create a dataframe. We have added another feature in the data frame named as 'Stock_Price'.
time_index = pd.date_range('21/09/2020', periods=6, freq='W')
df = pd.DataFrame(index=time_index)
df['Stock_Price'] = [100,200,300,400,500,600]
So here we have used rolling function with parameter window which signifies the number of rows the function will select to compute the statical measure. We have created two functions one will calculate the mean and other will calculate the max of all the rows which will be selected.
df1 = df.rolling(window=3).mean()
df2 = df.rolling(window=3).max()
So the output comes as
Stock_Price 2020-09-27 100 2020-10-04 200 2020-10-11 300 2020-10-18 400 2020-10-25 500 2020-11-01 600 Stock_Price 2020-09-27 NaN 2020-10-04 NaN 2020-10-11 200.0 2020-10-18 300.0 2020-10-25 400.0 2020-11-01 500.0 Stock_Price 2020-09-27 NaN 2020-10-04 NaN 2020-10-11 300.0 2020-10-18 400.0 2020-10-25 500.0 2020-11-01 600.0