Time Series • Introduction to Time Series
Time Series / P1.08 Prepare Historical Data

P1.08 Prepare Historical Data

Practical 1 Introduction to Time Series

A monthly series has a missing value and mixed types. Clean it into a regular datetime-indexed series ready for forecasting.

Practical / Solution

P1.08 Prepare Historical Data

Problem Statement

A monthly series has a missing value and mixed types. Clean it into a regular datetime-indexed series ready for forecasting.

Learning Outcomes

  • Parse dates.
  • Set a monthly frequency.
  • Handle one missing value in a transparent way.

Hint

Convert to datetime, set_index, asfreq('MS'), then interpolate or use a clearly stated fill method.

Theory

Preparation includes consistent frequency, numeric type, and a documented missing-value rule. Silent filling without comment is poor practice.

Dataset / Data Source

Teaching CSV-like rows: 2025-01, 20; 2025-02, 22; 2025-03, missing; 2025-04, 25; 2025-05, 24.

Analysis / Program

import pandas as pd raw = pd.DataFrame({ "month": ["2025-01", "2025-02", "2025-03", "2025-04", "2025-05"], "sales": ["20", "22", None, "25", "24"] }) raw["month"] = pd.to_datetime(raw["month"]) ts = raw.set_index("month")["sales"].astype(float).asfreq("MS") print("Before filling:") print(ts) # Linear interpolation for a single interior missing month clean = ts.interpolate(limit_direction="both") print("After interpolation:") print(clean)

Expected Output

A five-month series with NaN in March, then a filled March value between February and April.

Result / Interpretation

The cleaned series is regular and numeric. Interpolation is acceptable here because only one interior point is missing. Students must record the rule they used.

Note

Never start modelling on a series whose missing values have not been inspected.