0
0
Pandasdata~20 mins

rolling() for moving windows in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rolling Window Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of rolling mean with window size 3
What is the output of the following code snippet?
Pandas
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5])
result = s.rolling(window=3).mean()
print(result.tolist())
A[1.0, 1.5, 2.0, 3.0, 4.0]
B[nan, nan, nan, 2.0, 3.0]
C[nan, nan, 2.0, 3.0, 4.0]
D[nan, 2.0, 3.0, 4.0, 5.0]
Attempts:
2 left
💡 Hint
Remember that rolling mean with window=3 requires 3 values before it can compute the mean.
data_output
intermediate
2:00remaining
Count of rolling window sums greater than 10
Given the code below, how many rolling sums with window size 4 are greater than 10?
Pandas
import pandas as pd
s = pd.Series([2, 5, 3, 8, 7, 4, 6])
rolling_sum = s.rolling(window=4).sum()
count = (rolling_sum > 10).sum()
print(count)
A1
B3
C2
D4
Attempts:
2 left
💡 Hint
Calculate sums for windows: positions 3 to 6 and count how many exceed 10.
🔧 Debug
advanced
2:00remaining
Identify the error in rolling window code
What error does the following code produce?
Pandas
import pandas as pd
s = pd.Series([1, 2, 3, 4])
result = s.rolling(window=0).mean()
print(result)
AValueError: window must be >= 1
BTypeError: window must be an integer
CAttributeError: 'Series' object has no attribute 'rolling'
DNo error, prints rolling mean
Attempts:
2 left
💡 Hint
Check the window parameter value and its allowed range.
🚀 Application
advanced
2:30remaining
Using rolling to detect trends in stock prices
You have daily stock prices in a pandas Series. You want to create a new Series that shows the 5-day rolling average price but only for days where the average is higher than the previous day's average. Which code snippet correctly achieves this?
A
rolling_avg = prices.rolling(window=5).sum()
result = rolling_avg[rolling_avg > rolling_avg.shift(1)]
B
rolling_avg = prices.rolling(window=5).mean()
result = rolling_avg[rolling_avg > rolling_avg.shift(1)]
C
rolling_avg = prices.rolling(window=5).mean()
result = rolling_avg[rolling_avg == rolling_avg.shift(1)]
D
rolling_avg = prices.rolling(window=5).mean()
result = rolling_avg[rolling_avg < rolling_avg.shift(1)]
Attempts:
2 left
💡 Hint
Compare the rolling average to its previous value using shift(1).
🧠 Conceptual
expert
2:30remaining
Effect of min_periods in rolling windows
Consider a pandas Series with 6 values. You apply rolling(window=4, min_periods=2).sum(). How many values in the resulting Series will be non-NaN?
A5
B4
C3
D6
Attempts:
2 left
💡 Hint
min_periods=2 means the sum is computed if at least 2 values are present in the window.