WikiGalaxy

Personalize

Rolling and Expanding Operations in Pandas

Rolling and expanding operations in Pandas provide a way to perform calculations over a sliding window or cumulative calculations over a dataset. These operations are useful for time series data analysis, allowing you to compute statistics like moving averages, rolling sums, and expanding means.

Rolling Mean

The rolling mean is a common operation used to smooth out short-term fluctuations and highlight longer-term trends in data.


import pandas as pd

data = {'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(data)
df['rolling_mean'] = df['value'].rolling(window=3).mean()
print(df)
        

In this example, a rolling window of size 3 is used to calculate the mean. The result is a new column with the rolling mean values.

Rolling Sum

The rolling sum calculates the sum of values within a specified window, which can be used to analyze cumulative changes over time.


import pandas as pd

data = {'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(data)
df['rolling_sum'] = df['value'].rolling(window=4).sum()
print(df)
        

Here, a rolling window of size 4 is used to compute the sum, resulting in a new column with the rolling sum values.

Expanding Mean

The expanding mean calculates the mean of all data points up to the current point, providing a cumulative average.


import pandas as pd

data = {'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(data)
df['expanding_mean'] = df['value'].expanding().mean()
print(df)
        

This example demonstrates the use of the expanding function to calculate a cumulative mean, adding a new column with these values to the DataFrame.

Expanding Sum

The expanding sum computes the cumulative sum of all values up to the current point, useful for tracking total accumulation over time.


import pandas as pd

data = {'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(data)
df['expanding_sum'] = df['value'].expanding().sum()
print(df)
        

In this case, the expanding function is used to calculate a cumulative sum, which is then stored in a new column of the DataFrame.

Rolling Standard Deviation

The rolling standard deviation helps measure the variability of data points within a specific window, providing insights into volatility.


import pandas as pd

data = {'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(data)
df['rolling_std'] = df['value'].rolling(window=5).std()
print(df)
        

This example illustrates how to compute the rolling standard deviation over a window of size 5, adding the results to a new column.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025