0
0
Data Analysis Pythondata~5 mins

Rolling window calculations in Data Analysis Python

Choose your learning style9 modes available
Introduction

Rolling window calculations help you see trends by looking at small groups of data points over time.

To smooth noisy data like daily temperatures or stock prices.
To find moving averages in sales data to understand trends.
To calculate rolling sums or counts in time series data.
To detect changes or patterns in sensor readings over time.
To compare recent data with past data in a sliding window.
Syntax
Data Analysis Python
df['column'].rolling(window=n).function()

window=n sets how many data points to include in each calculation.

You can use functions like mean(), sum(), min(), max(), and more.

Examples
Calculates the average of every 3 sales values in a rolling window.
Data Analysis Python
df['sales'].rolling(window=3).mean()
Calculates the sum of every 5 temperature readings in a rolling window.
Data Analysis Python
df['temperature'].rolling(window=5).sum()
Finds the highest price in each group of 4 consecutive prices.
Data Analysis Python
df['price'].rolling(window=4).max()
Sample Program

This program creates a small sales dataset and calculates the 3-day rolling average of sales. It shows how the average changes as the window moves.

Data Analysis Python
import pandas as pd

data = {'day': [1, 2, 3, 4, 5, 6],
        'sales': [10, 20, 30, 40, 50, 60]}
df = pd.DataFrame(data)

# Calculate 3-day rolling average of sales
df['rolling_avg'] = df['sales'].rolling(window=3).mean()

print(df)
OutputSuccess
Important Notes

The first window-1 results are NaN because there is not enough data to fill the window.

You can change the min_periods parameter to get results with fewer points in the window.

Summary

Rolling window calculations help analyze data trends over small groups of points.

Use rolling(window=n) with functions like mean() or sum().

They are useful for smoothing data and finding patterns in time series.