Bird
Raised Fist0
Pandasdata~20 mins

Expanding window operations in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Expanding Window Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of expanding sum with min_periods
What is the output of the following code snippet using pandas expanding sum with min_periods=2?
Pandas
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5])
result = s.expanding(min_periods=2).sum()
print(result.tolist())
A[nan, nan, 6.0, 10.0, 15.0]
B[1.0, 3.0, 6.0, 10.0, 15.0]
C[1, 3, 6, 10, 15]
D[nan, 3.0, 6.0, 10.0, 15.0]
Attempts:
2 left
💡 Hint
Remember that min_periods=2 means the expanding window will return NaN until at least 2 values are included.
❓ data_output
intermediate
1:30remaining
Length of expanding window result
Given a pandas Series of length 7, what is the length of the Series returned by expanding().mean()?
Pandas
import pandas as pd
s = pd.Series(range(7))
result = s.expanding().mean()
print(len(result))
A7
B6
C8
D0
Attempts:
2 left
💡 Hint
The expanding window operation returns a result for each original element.
🔧 Debug
advanced
2:00remaining
Identify the error in expanding window code
What error does the following code raise when executed?
Pandas
import pandas as pd
s = pd.Series([1, 2, 3])
result = s.expanding(min_periods=0).sum()
print(result)
AAttributeError: 'Series' object has no attribute 'expanding'
BValueError: min_periods must be >= 1
CNo error, prints [1, 3, 6]
DTypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Attempts:
2 left
💡 Hint
Check the allowed values for the min_periods parameter in expanding.
❓ visualization
advanced
2:30remaining
Plotting expanding mean of a time series
Which option produces a line plot showing the original data and its expanding mean on the same graph?
Pandas
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series([2, 4, 6, 8, 10])
exp_mean = s.expanding().mean()
plt.figure()
plt.plot(s, label='Original')
plt.plot(exp_mean, label='Expanding Mean')
plt.legend()
plt.show()
AThe plot shows two lines but both are flat at zero.
BThe plot shows only one line identical to the original data.
CThe plot shows two lines: the original increasing values and a smoother line starting at the first value and gradually increasing.
DThe plot shows an error because matplotlib is not imported.
Attempts:
2 left
💡 Hint
The expanding mean smooths the data by averaging all values up to each point.
🚀 Application
expert
3:00remaining
Using expanding window to detect trend changes
You have daily sales data in a pandas Series. You want to detect when the sales trend changes by comparing the expanding mean to the current value. Which code snippet correctly creates a boolean Series indicating if the current value is above the expanding mean?
Asales > sales.expanding().mean()
Bsales.expanding().mean() > sales
Csales > sales.rolling(window=3).mean()
Dsales.expanding(min_periods=0).mean() > sales
Attempts:
2 left
💡 Hint
Expanding mean includes all data up to current point; compare current value to it.

Practice

(1/5)
1. What does an expanding window operation in pandas do?
easy
A. Sorts data in ascending order
B. Calculates values only for a fixed-size sliding window
C. Filters data based on a condition
D. Calculates cumulative values including all previous data points

Solution

  1. Step 1: Understand expanding window concept

    Expanding window operations include all data points from the start up to the current point.
  2. Step 2: Compare with other window types

    Unlike rolling windows, expanding windows grow with each step, accumulating more data.
  3. Final Answer:

    Calculates cumulative values including all previous data points -> Option D
  4. Quick Check:

    Expanding window = cumulative calculation [OK]
Hint: Expanding means cumulative from start to current [OK]
Common Mistakes:
  • Confusing expanding with rolling window
  • Thinking it filters data
  • Assuming it sorts data
2. Which of the following is the correct syntax to create an expanding window object on a pandas Series s?
easy
A. s.window()
B. s.expanding()
C. s.cumulative()
D. s.rolling()

Solution

  1. Step 1: Recall pandas expanding syntax

    The method to create an expanding window object is expanding() called on a Series or DataFrame.
  2. Step 2: Eliminate incorrect options

    rolling() is for rolling windows, cumulative() and window() do not exist as methods.
  3. Final Answer:

    s.expanding() -> Option B
  4. Quick Check:

    Use .expanding() for expanding windows [OK]
Hint: Use .expanding() method on Series/DataFrame [OK]
Common Mistakes:
  • Using .rolling() instead of .expanding()
  • Trying non-existent methods like .cumulative()
  • Confusing window types
3. Given the pandas Series s = pd.Series([2, 4, 6, 8]), what is the output of s.expanding(min_periods=2).mean()?
medium
A. [NaN, 3.0, 4.0, 5.0]
B. [2.0, 3.0, 4.0, 5.0]
C. [NaN, 4.0, 6.0, 8.0]
D. [2.0, 4.0, 6.0, 8.0]

Solution

  1. Step 1: Understand min_periods effect

    With min_periods=2, results start from the second element; first is NaN.
  2. Step 2: Calculate expanding mean values

    Means are: index 1: (2+4)/2=3.0, index 2: (2+4+6)/3=4.0, index 3: (2+4+6+8)/4=5.0.
  3. Final Answer:

    [NaN, 3.0, 4.0, 5.0] -> Option A
  4. Quick Check:

    Expanding mean with min_periods=2 starts NaN then cumulative means [OK]
Hint: min_periods controls when output starts (NaN before) [OK]
Common Mistakes:
  • Ignoring min_periods and showing first value
  • Calculating rolling mean instead of expanding mean
  • Miscomputing cumulative averages
4. What is wrong with this code snippet?
import pandas as pd
s = pd.Series([1, 2, 3])
result = s.expanding(min_periods=-1).sum()
medium
A. sum() cannot be used after expanding()
B. expanding() method does not exist for Series
C. min_periods cannot be negative; it must be >= 0
D. The Series must be converted to DataFrame first

Solution

  1. Step 1: Check min_periods parameter rules

    min_periods must be >= 0; negative is invalid and causes an error.
  2. Step 2: Verify method usage

    expanding() exists for Series, and sum() is valid after expanding().
  3. Final Answer:

    min_periods cannot be negative; it must be >= 0 -> Option C
  4. Quick Check:

    min_periods ≥ 0 required [OK]
Hint: min_periods must be >= 0, never negative [OK]
Common Mistakes:
  • Setting min_periods to a negative value causing errors
  • Thinking expanding() is unavailable for Series
  • Misusing sum() after expanding()
5. You have daily sales data in a pandas DataFrame df with a column 'sales'. You want to calculate a running average of sales but only start showing results after at least 3 days of data. Which code correctly achieves this using expanding window operations?
hard
A. df['sales'].expanding(min_periods=3).mean()
B. df['sales'].rolling(window=3).mean()
C. df['sales'].expanding(min_periods=1).mean()
D. df['sales'].cumsum() / 3

Solution

  1. Step 1: Understand requirement for running average with minimum data

    Expanding with min_periods=3 starts calculating mean only after 3 data points.
  2. Step 2: Evaluate options

    df['sales'].expanding(min_periods=3).mean() uses expanding with min_periods=3 correctly. df['sales'].rolling(window=3).mean() uses rolling window, which is different. df['sales'].expanding(min_periods=1).mean() starts from 1 data point, not 3. df['sales'].cumsum() / 3 divides cumulative sum by 3 always, which is incorrect.
  3. Final Answer:

    df['sales'].expanding(min_periods=3).mean() -> Option A
  4. Quick Check:

    Expanding with min_periods=3 for running average [OK]
Hint: Use expanding(min_periods=3) for running average after 3 days [OK]
Common Mistakes:
  • Using rolling instead of expanding
  • Setting min_periods too low
  • Dividing cumulative sum by fixed number
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard