TExcelTAD

Preparing Time-Series Data

In a time series, order is the information. Rows are not independent samples: today's value is close to yesterday's, and the whole point is usually to predict what comes next. That changes the preparation rules. Rows must be sorted, gaps in time must be made visible, the series often needs a regular frequency, features may only look backwards, and the test period must come after the training period. Every one of these steps has a way of letting the future leak in. Time Series Data introduced the data type; this lesson prepares it.

Sort, deduplicate and expose the gaps

Sensor logs and event exports are rarely clean: rows arrive out of order, a retry writes the same reading twice, a device goes offline for hours, and intervals drift. Make each problem explicit before anything else.

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
ts = pd.date_range("2026-03-01 00:00", periods=48, freq="h")
ts = ts + pd.to_timedelta(rng.integers(-4, 5, 48), unit="min")      # irregular: readings drift
temp = 20 + 4 * np.sin(np.arange(48) / 24 * 2 * np.pi) + rng.normal(0, 0.3, 48)
log = pd.DataFrame({"time": ts, "temp": temp.round(2)})
log = log.drop(index=range(20, 26))                                   # 6 hours offline
log = pd.concat([log, log.iloc[[3]]])                                 # a duplicated reading
log = log.sample(frac=1, random_state=1)                              # arrives shuffled

print("sorted on arrival?", log["time"].is_monotonic_increasing, "| rows:", len(log))
log = log.sort_values("time").drop_duplicates(subset="time")
gaps = log["time"].diff()
print("rows after sort + dedupe:", len(log))
print("median interval:", gaps.median(), "| largest gap:", gaps.max())

raw_bins = log.set_index("time")["temp"].resample("h").mean()
print("hourly bins of raw times with no reading:", int(raw_bins.isna().sum()))
log["time"] = log["time"].dt.round("h")                               # snap the drift first
hourly = log.set_index("time")["temp"].resample("h").mean()           # regular frequency
print("after rounding to the hour:", len(hourly), "hours,", int(hourly.isna().sum()), "with no reading")
print("forward fill (causal) at 22:00:", round(float(hourly.ffill()["2026-03-01 22:00"]), 2))
print("interpolation (uses the future) at 22:00:", round(float(hourly.interpolate()["2026-03-01 22:00"]), 2))
sorted on arrival? False | rows: 43
rows after sort + dedupe: 42
median interval: 0 days 01:00:00 | largest gap: 0 days 06:56:00
hourly bins of raw times with no reading: 12
after rounding to the hour: 48 hours, 6 with no reading
forward fill (causal) at 22:00: 16.37
interpolation (uses the future) at 22:00: 18.83

The log arrived unsorted, with 43 rows. Sorting and dropping the duplicated timestamp leaves 42 readings. The median interval is one hour, but the largest gap is 6 h 56 min: the device was offline. Resampling the raw timestamps straight into hourly bins reports 12 empty hours, not 6, because a reading taken at 05:57 falls into the 05:00 bin and leaves the 06:00 bin empty. Snapping the drifting timestamps to the nearest hour first gives the true picture: 48 hours, 6 without a reading. To fill them, forward fill uses only the past (16.37 at 22:00, the last value before the outage); linear interpolation gives 18.83 because it already knows the reading at the end of the outage, information a live forecast at 22:00 would not have had.

Resampling to a regular frequency gives every time step a row. Choose the aggregation by meaning: a temperature is averaged (mean), a sales count is summed (sum), a price is often the last value of the period (last). Mark filled gaps with an indicator column, so the model knows which values were invented.

Lag and rolling features that only look back

A forecasting model may use anything known at the moment of the forecast, never anything later. Lag features (shift(1), shift(24)) and rolling statistics are the standard inputs (Lag, Rolling and Group Aggregation Features covers them in depth). The classic mistake is a rolling window that includes the current value or, worse, is centred, so that it averages future values into today's feature.

The example predicts tomorrow's demand from daily data with a weekly pattern and a slow trend. It compares honest features with a centred 3-day mean, evaluated with TimeSeriesSplit, which always trains on the past and tests on the following block.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge
from sklearn.model_selection import TimeSeriesSplit, cross_val_score

rng = np.random.default_rng(1)
days = pd.date_range("2025-01-01", periods=500, freq="D")
level = np.cumsum(rng.normal(0, 1.5, 500))                         # wandering level
weekly = 8 * np.sin(2 * np.pi * days.dayofweek / 7)
df = pd.DataFrame({"demand": 100 + level + weekly + rng.normal(0, 2, 500)}, index=days)

df["target"] = df["demand"].shift(-1)                                # tomorrow
df["lag_0"] = df["demand"]                                           # today: known at prediction time
df["lag_1"] = df["demand"].shift(1)                                  # yesterday
df["lag_6"] = df["demand"].shift(6)                                  # tomorrow's weekday, a week earlier
df["mean_3_past"] = df["demand"].rolling(3).mean()                   # today and 2 days back
df["mean_3_centred"] = df["demand"].rolling(3, center=True).mean()   # LEAK: includes tomorrow
df["dow"] = df.index.dayofweek
data = df.dropna()

honest = ["lag_0", "lag_1", "lag_6", "mean_3_past", "dow"]
leaky = ["lag_0", "lag_1", "lag_6", "mean_3_centred", "dow"]
tscv = TimeSeriesSplit(n_splits=5, gap=0)
for name, cols in [("honest features", honest), ("centred rolling mean", leaky)]:
    mae = -cross_val_score(Ridge(alpha=1.0), data[cols], data["target"], cv=tscv,
                           scoring="neg_mean_absolute_error").mean()
    print(f"{name:21s} MAE {mae:.2f}")

for i, (tr, te) in enumerate(tscv.split(data)):
    if i in (0, 4):
        print(f"fold {i}: train {data.index[tr[0]].date()} .. {data.index[tr[-1]].date()}, "
              f"test {data.index[te[0]].date()} .. {data.index[te[-1]].date()}")
honest features       MAE 3.06
centred rolling mean  MAE 0.02
fold 0: train 2025-01-07 .. 2025-03-30, test 2025-03-31 .. 2025-06-20
fold 4: train 2025-01-07 .. 2026-02-21, test 2026-02-22 .. 2026-05-14

With honest features, the mean absolute error is 3.06 demand units. With the centred 3-day mean, it drops to 0.02, a near-perfect forecast that is pure leakage: the centred window is (yesterday + today + tomorrow) / 3, and with yesterday and today also among the features, a linear model can solve for tomorrow exactly. Real leaks are rarely this clean, but they work the same way. The fold lines show how TimeSeriesSplit moves forward: fold 0 trains on 2025-01-07 to 2025-03-30 and tests on the next block; fold 4 trains on everything up to 2026-02-21 and tests on the last block.

Note: TimeSeriesSplit(gap=k) leaves k rows out between training and test. Use a gap when the target spans several steps (predicting the next 7 days) or features use long windows, so the last training rows do not share information with the first test rows.

Scaling, imputing and encoding: fit on the past

Every fitted step (a scaler, an imputer, a target encoding) is fitted on the training period and applied to later periods, inside a pipeline evaluated with TimeSeriesSplit. Statistics computed over the whole series, even an innocent-looking (x - x.mean()) / x.std(), include the future. For deployment, also simulate the delay: if yesterday's sales arrive in the database only at noon, a feature "yesterday's sales" is not available for a 9 a.m. forecast.

Many series at once

With one series per store, sensor or customer, compute lags and rolling features per series (df.groupby("store")["sales"].shift(1)), and split by time for all of them together, with the same cut-off date. Splitting by series instead (some stores in training, others in test) answers a different question, "how well does it work for a new store?", and is also valid when that is the question.

Pitfalls

  • Unsorted rows: shift and rolling follow row order, not time. Sort first.
  • Centred windows or windows including the target time: future information in the features.
  • Interpolating gaps for a forecasting model: interpolation uses the next observed value; prefer forward fill plus an indicator.
  • Random K-fold on a time series: the model interpolates between neighbouring days; the leakage lab shows the inflated R-squared.
  • Whole-series statistics: scalers and encoders must be fitted on the training period.

Practice

  1. A rolling feature is written df["mean_3"] = df["y"].rolling(3).mean() and the target is df["y"] (today's value). What is wrong, and how do you fix it?
Answer

The window includes today's y, the very value to predict. Shift it: df["y"].shift(1).rolling(3).mean() uses the three previous days only.

  1. Hourly electricity readings have a 3-hour gap. You train a model that forecasts the next hour. How do you fill the gap, and what extra column do you add?
Answer

Forward fill (or a seasonal value from the same hour of the previous day), never interpolation, because the forecast at those hours could not have known the later reading. Add an indicator column was_missing so the model can discount filled values.

Test yourself

Which split should be used to evaluate a forecasting model?

  1. Shuffled K-fold
  2. Stratified K-fold
  3. Train on earlier periods, test on later ones (e.g. TimeSeriesSplit)
  4. Leave-one-out at random

Why is rolling(7, center=True).mean() a leak for forecasting?

  1. It is too smooth
  2. It averages values from days after the prediction time
  3. It drops the first rows
  4. It needs more memory

Readings arrive out of order. What must happen before shift(1) creates lag features?

  1. Nothing
  2. Sort by time (and remove duplicate timestamps)
  3. Scale the values
  4. Resample to weekly

Hourly sales are resampled to daily totals. Which aggregation fits?

  1. mean
  2. sum
  3. first
  4. max