Pandas DataFrame.rolling: Rolling Window Calculations on a DataFrame
Pandas DataFrame.rolling
The DataFrame.rolling method in pandas is used to perform rolling window calculations on a DataFrame. It allows you to apply operations (e.g., mean, sum, etc.) over a sliding window of rows or columns.
Syntax
The syntax for DataFrame.rolling is:
DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, step=None, method='single')Here, DataFrame refers to the pandas DataFrame on which the rolling window calculations are performed.
Parameters
| Parameter | Description |
|---|---|
window | Specifies the size of the moving window. This can be an integer (fixed window size) or an offset (variable window size based on time). |
min_periods | Specifies the minimum number of observations in the window required to have a value. Defaults to the window size. |
center | If True, the window is centered on the current observation. Defaults to False. |
win_type | Specifies the type of window (e.g., 'triang', 'blackman', etc.). Defaults to None (uniform weights). |
on | Specifies the column to use for rolling calculations when the DataFrame is indexed by time. |
axis | Specifies the axis along which the rolling window is applied. Use 0 or 'index' for rows, and 1 or 'columns' for columns. Defaults to 0. |
closed | Specifies whether the window is closed on the left, right, both, or neither. Options include 'right', 'left', 'both', or 'neither'. Defaults to None. |
step | Specifies the step size for the rolling window. Defaults to None. |
method | Specifies the method for handling overlapping windows. Options include 'single' or 'table'. Defaults to 'single'. |
Returns
A Rolling object, which can be used to apply aggregation or transformation operations over the rolling window.
Examples
Rolling Mean Calculation on a DataFrame
This example demonstrates how to use rolling to calculate the rolling mean of a DataFrame column with a window size of 3.
Python Program
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Values': [1, 2, 3, 4, 5, 6, 7, 8, 9]})
# Calculate the rolling mean with a window size of 3
result = df['Values'].rolling(window=3).mean()
print(result)Output
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
5 5.0
6 6.0
7 7.0
8 8.0
Name: Values, dtype: float64Rolling Sum Calculation on a DataFrame
This example shows how to use rolling to calculate the rolling sum of a DataFrame column with a window size of 2.
Python Program
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Values': [10, 20, 30, 40, 50]})
# Calculate the rolling sum with a window size of 2
result = df['Values'].rolling(window=2).sum()
print(result)Output
0 NaN
1 30.0
2 50.0
3 70.0
4 90.0
Name: Values, dtype: float64Rolling Window Calculation with a Time-Based Offset
This example demonstrates how to use rolling with a time-based offset to calculate the rolling mean of a DataFrame indexed by dates.
Python Program
import pandas as pd
# Create a DataFrame with a date index
dates = pd.date_range('2023-01-01', periods=5, freq='D')
df = pd.DataFrame({'Values': [1, 2, 3, 4, 5]}, index=dates)
# Calculate the rolling mean with a 2-day window
result = df['Values'].rolling(window='2D').mean()
print(result)Output
2023-01-01 1.0
2023-01-02 1.5
2023-01-03 2.5
2023-01-04 3.5
2023-01-05 4.5
Freq: D, Name: Values, dtype: float64Rolling Window Calculation with Custom Window Type
This example shows how to use rolling with a custom window type (e.g., triangular window) to calculate the rolling weighted mean of a DataFrame column.
Python Program
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'Values': [1, 2, 3, 4, 5, 6, 7, 8, 9]})
# Calculate the rolling weighted mean with a triangular window
result = df['Values'].rolling(window=3, win_type='triang').mean()
print(result)Output
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
5 5.0
6 6.0
7 7.0
8 8.0
Name: Values, dtype: float64Summary
In this tutorial, we explored the DataFrame.rolling method in pandas. Key takeaways include:
- Using
rollingto perform rolling window calculations on a DataFrame. - Applying aggregation functions (e.g., mean, sum) over a sliding window.
- Using time-based offsets and custom window types for advanced rolling calculations.
- Understanding the parameters of
rolling, such aswindow,min_periods, andwin_type.