How to Get a Rolling Mean From a pandas DataFrame in Python
A rolling mean is an average from a window based on a series of sequential values from the data in a DataFrame.
To get a rolling mean from a pandas
DataFrame in Python, use the pandas.DataFrame.rolling()
function. Pass the window as the first argument and the minimum periods as the second.
rolling_windows = pandas.DataFrame.rolling(window, min_periods)
Then call the pandas.Rolling.mean()
function on the result of the last function to get a new DataFrame containing the rolling mean from the original DataFrame.
rolling_mean = rolling_windows.mean()
Let's try this out with a pandas
DataFrame containing some simple data.
import pandas as pd
d = {0,1,2,3}
df = pd.DataFrame(data=d)
rolling_windows = df.rolling(2, min_periods=1)
rolling_mean = rolling_windows.mean()
print(rolling_mean)
0
0 0.0
1 0.5
2 1.5
3 2.5
pandas
machine learning