0
0
Pandasdata~5 mins

Rolling standard deviation in Pandas

Choose your learning style9 modes available
Introduction

Rolling standard deviation helps you see how data changes over time by calculating variability in small moving windows.

To track how stock price volatility changes day by day.
To monitor temperature fluctuations over a week in weather data.
To analyze sensor data variability in a moving time frame.
To detect changes in sales variability over recent months.
Syntax
Pandas
DataFrame['column'].rolling(window).std()

window is the size of the moving window (number of rows).

The result shows the standard deviation for each window as it moves down the data.

Examples
Calculates rolling standard deviation with a window of 3 rows on the 'price' column.
Pandas
df['price'].rolling(3).std()
Calculates rolling standard deviation over 5 rows for the 'temp' column.
Pandas
df['temp'].rolling(window=5).std()
Calculates rolling standard deviation with a window size of 4 on 'sensor' data.
Pandas
df['sensor'].rolling(4).std()
Sample Program

This code creates a small sales dataset and calculates the rolling standard deviation over 3 days. It shows how sales variability changes in each 3-day window.

Pandas
import pandas as pd

data = {'day': [1, 2, 3, 4, 5, 6], 'sales': [10, 12, 14, 13, 15, 16]}
df = pd.DataFrame(data)

# Calculate rolling standard deviation with window size 3
rolling_std = df['sales'].rolling(3).std()

print(rolling_std)
OutputSuccess
Important Notes

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

You can change the window size to see variability over different time spans.

Summary

Rolling standard deviation measures variability in moving windows.

It helps track changes in data spread over time.

Use rolling(window).std() on a pandas Series or DataFrame column.