Back to Practice
#0118

Rolling Average by User

MediumPandas25 min20 XP

Problem

Given user_id, day, and value, return a copy sorted by user_id/day with avg_2 equal to the rolling mean of the current and previous row for that user.

Why This Matters

Rolling features are common in time series, product analytics, and ML feature engineering.

Function Signature

def add_rolling_avg_2(df):

Examples

Example 1
Inputuser 1 values 10, 20, 30
Outputavg_2 values 10, 15, 25

Each value averages with the previous value for the same user when available.

Constraints

  • Return the requested value exactly.
  • Handle the stated edge cases.
  • Keep the solution readable.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputuser 1 values 10, 20, 30
Expectedavg_2 values 10, 15, 25

Each value averages with the previous value for the same user when available.

Hidden Test Categories
multiple usersunsorted inputsingle row per user