To calculate a rolling average in Python, we can use the pandas library which provides an easy-to-use rolling function that can be applied to a DataFrame or Series.
main.py249 chars10 lines
In this code, we first import pandas library. Then, we create a sample dataframe with two columns A and B. We use the "rolling" function to calculate the rolling average on column A with a window size of 3. Finally, we add a new column called "rolling_avg" to the dataframe which contains the rolling average values.
The output of this code would be:
main.py154 chars8 lines
Note that, since we used a window size of 3, the first two rows of the "rolling_avg" column have a value of NaN, since there are not enough values in the window to calculate the rolling average.
gistlibby LogSnag