Rolling mean and sum in Pandas - Time & Space Complexity
We want to understand how the time to calculate rolling mean and sum changes as the data size grows.
How does the work increase when we have more data points?
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # Example value for n
data = pd.Series(range(1, n+1))
window_size = 3
rolling_mean = data.rolling(window=window_size).mean()
rolling_sum = data.rolling(window=window_size).sum()
This code calculates the rolling mean and sum over a sliding window of size 3 on a series of length n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: For each position in the data, the window of size 3 is processed to compute mean and sum.
- How many times: This happens once for each of the n data points (except the first few where the window is incomplete).
As the data size n grows, the number of operations grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the window size (3) |
| 100 | About 100 times the window size (3) |
| 1000 | About 1000 times the window size (3) |
Pattern observation: The total work grows linearly with n because each new data point requires a fixed amount of work related to the window size.
Time Complexity: O(n)
This means the time to compute rolling mean and sum grows in direct proportion to the number of data points.
[X] Wrong: "Calculating rolling mean and sum takes time proportional to n times the window size squared."
[OK] Correct: The window size is fixed and small, so it does not multiply the work by itself. The main growth depends on n, not on window size squared.
Understanding how rolling calculations scale helps you explain performance when working with time series or streaming data in real projects.
"What if the window size grew proportionally with n? How would the time complexity change?"
Practice
rolling(window=3).mean() function do on a pandas Series?Solution
Step 1: Understand rolling window size
The window=3 means we look at 3 values at a time: the current and previous 2.Step 2: Apply mean function on each window
For each position, the mean is calculated over these 3 values, smoothing the data.Final Answer:
Calculates the average of the current and previous 2 values for each position. -> Option AQuick Check:
Rolling mean = average over window [OK]
- Thinking it sums all values, not just window
- Confusing mean with difference
- Assuming it sorts data
'sales'?Solution
Step 1: Identify correct method chaining
In pandas, rolling is called on the Series, then sum() is applied.Step 2: Check syntax correctness
df['sales'].rolling(4).sum() correctly uses df['sales'].rolling(4).sum() which is valid syntax.Final Answer:
df['sales'].rolling(4).sum() -> Option CQuick Check:
Correct rolling sum syntax = df['sales'].rolling(4).sum() [OK]
- Passing column name as string to rolling()
- Calling sum() before rolling()
- Using undefined rolling() function
data = pd.Series([2, 4, 6, 8, 10]), what is the output of data.rolling(window=3).sum()?Solution
Step 1: Understand rolling sum with window=3
For the first two positions, there are not enough values to fill the window, so result is NaN.Step 2: Calculate sums for positions 3 to 5
Position 3 sum: 2+4+6=12, position 4 sum: 4+6+8=18, position 5 sum: 6+8+10=24.Final Answer:
[NaN, NaN, 12, 18, 24] -> Option DQuick Check:
Rolling sum with window=3 pads start with NaN [OK]
- Expecting sums from first element
- Confusing rolling sum with cumulative sum
- Ignoring NaN for incomplete windows
'temp' with window 2?df = pd.DataFrame({'temp': [10, 20, 30]})
df['rolling_mean'] = df.rolling(2).mean()['temp']Solution
Step 1: Analyze the code execution
df.rolling(2).mean() applies the rolling mean to the 'temp' column, producing a DataFrame with values [NaN, 15.0, 25.0].Step 2: Column access and assignment
df.rolling(2).mean()['temp'] extracts the Series correctly, and assignment to df['rolling_mean'] succeeds without errors.Final Answer:
The code is correct and will run without errors. -> Option AQuick Check:
df.rolling(2).mean()['temp'] works for column rolling mean [OK]
- Believing rolling() must only be called on Series
- Thinking window size must be 3 or more
- Assuming mean() cannot be used after rolling()
df with column 'sales'. You want to create a new column 'weekly_avg' that shows the average sales over the last 7 days, but only if at least 5 days of data are available in the window. Which code correctly achieves this?Solution
Step 1: Understand rolling with min_periods
min_periods=5 means the rolling function will compute mean only if at least 5 values exist in the window.Step 2: Check correct syntax for rolling mean with conditions
df['weekly_avg'] = df['sales'].rolling(window=7, min_periods=5).mean() correctly uses rolling(window=7, min_periods=5).mean() to get average over 7 days with minimum 5 days data.Final Answer:
df['weekly_avg'] = df['sales'].rolling(window=7, min_periods=5).mean() -> Option BQuick Check:
Use min_periods to require minimum data in rolling [OK]
- Passing min_periods to mean() instead of rolling()
- Using wrong window size
- Dividing sum by fixed number ignoring data count
Ready to prove it?
Pass the test and this pattern moves unknown
