Rolling mean and sum help you see trends by averaging or adding values over a moving window of data points.
0
0
Rolling mean and sum in Pandas
Introduction
To smooth noisy daily sales data and see overall trends.
To calculate average temperature over the last 7 days.
To find the total rainfall in the past week from daily records.
To analyze stock prices by averaging over recent days.
To monitor moving totals or averages in sensor data for patterns.
Syntax
Pandas
df['column_name'].rolling(window=n).mean() df['column_name'].rolling(window=n).sum()
window=n sets how many data points to include in each calculation.
Rolling calculations move one step at a time over the data.
Examples
Calculates the average of sales over the last 3 rows for each row.
Pandas
df['sales'].rolling(window=3).mean()
Calculates the total temperature over the last 5 rows for each row.
Pandas
df['temperature'].rolling(window=5).sum()
Finds the rolling average price over 4 data points.
Pandas
df['price'].rolling(window=4).mean()
Sample Program
This code creates a simple sales dataset and calculates the rolling mean and sum over a window of 3 days. It prints both results so you can see how the values change as the window moves.
Pandas
import pandas as pd data = {'day': [1, 2, 3, 4, 5, 6], 'sales': [10, 20, 30, 40, 50, 60]} df = pd.DataFrame(data) # Calculate rolling mean with window 3 rolling_mean = df['sales'].rolling(window=3).mean() # Calculate rolling sum with window 3 rolling_sum = df['sales'].rolling(window=3).sum() print('Rolling Mean (window=3):') print(rolling_mean) print('\nRolling Sum (window=3):') print(rolling_sum)
OutputSuccess
Important Notes
The first few results are NaN because there are not enough data points to fill the window.
You can change the window size to include more or fewer data points.
Summary
Rolling mean and sum calculate averages or totals over a moving window.
They help smooth data and reveal trends over time.
Use rolling(window=n) with .mean() or .sum() on pandas columns.