pandas: Lag and Rolling Features

medium
Unit 9 · Pandas II0/3 to milestone

Forecasting models need features from the past, such as yesterday's sales and last week's average, computed separately for each store and without peeking at the future.

Given a DataFrame with columns store, date and sales (in any order), implement add_lag_features(df) that returns a new DataFrame:

  • sorted by store, then date, with a fresh index;
  • lag_1: the store's sales on its previous row;
  • rolling_mean_3: the mean of the store's previous 3 rows (not including the current one), requiring all 3 to exist;
  • values that can't be computed are NaN. Don't modify the input DataFrame.
#pandas#time-series#feature-engineering2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
pandas: Lag and Rolling Features · TechGradify