rolling() for moving windows in Pandas - Time & Space Complexity
We want to understand how the time it takes to calculate rolling windows changes as the data grows.
How does the work increase when we have more rows in our data?
Analyze the time complexity of the following code snippet.
import pandas as pd
data = pd.Series(range(1_000))
rolling_mean = data.rolling(window=5).mean()
This code calculates the moving average over a window of 5 rows for a series of 1,000 numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: For each row, calculate the mean of the current window of 5 values.
- How many times: This happens once for each row starting from the 5th row to the end (about n times).
As the number of rows grows, the total work grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calculations of 5 values each |
| 100 | About 100 calculations of 5 values each |
| 1000 | About 1000 calculations of 5 values each |
Pattern observation: The total work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to compute the rolling mean grows in a straight line as the data size grows.
[X] Wrong: "Calculating rolling means takes the same time no matter how big the data is."
[OK] Correct: The calculation must be done for each row, so more rows mean more work and more time.
Understanding how rolling window calculations scale helps you explain performance in data tasks clearly and confidently.
"What if we change the window size from 5 to 50? How would the time complexity change?"