TExcelTAD

Time Series Data

A time series is a sequence of measurements taken in time order: the temperature every hour, a shop's sales per day, a heart rate sensor sampled 50 times a second, a share price per minute. What makes it different from an ordinary table is that the order of the rows carries information. Shuffle a table of patients and nothing is lost; shuffle a week of hourly temperatures and the daily cycle disappears.

What a time series looks like

In code, a time series is a column of values with a time index. pandas has a dedicated index type, DatetimeIndex, and the pandas datetime and resample lessons show its tools in detail.

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

rng = np.random.default_rng(0)
hours = pd.date_range("2026-03-02 00:00", periods=72, freq="h")
daily_cycle = 18 + 6 * np.sin(2 * np.pi * (hours.hour - 9) / 24)
temp = pd.Series(np.round(daily_cycle + rng.normal(0, 0.8, 72), 1), index=hours, name="temp_c")

print(temp.head(4))
print()
print("frequency:", temp.index.freqstr, "| start:", temp.index[0], "| end:", temp.index[-1])
print("daily mean:", temp.resample("D").mean().round(2).tolist())
print("warmest hour of day on average:", temp.groupby(temp.index.hour).mean().idxmax())
2026-03-02 00:00:00    13.9
2026-03-02 01:00:00    12.7
2026-03-02 02:00:00    12.7
2026-03-02 03:00:00    12.1
Freq: h, Name: temp_c, dtype: float64

frequency: h | start: 2026-03-02 00:00:00 | end: 2026-03-04 23:00:00
daily mean: [17.92, 18.2, 18.11]
warmest hour of day on average: 14

The three daily means are similar (17.92, 18.2 and 18.11 °C), and the warmest hour on average comes out as 14:00, next to the 15:00 peak built into the cycle; the random noise moves it by an hour. Both answers need the timestamps: without them the 72 numbers are just a list.

Vocabulary

Term Meaning
timestamp the time of one measurement; store it with a time zone when data comes from several places
frequency / sampling rate how often values are recorded: hourly (h), daily (D), 50 Hz
regular vs irregular fixed spacing (a sensor every second) vs events at any time (purchases, clicks)
univariate vs multivariate one value per time step vs several (temperature, humidity, wind together)
trend slow long-term change
seasonality a repeating pattern: daily, weekly, yearly
lag the value some steps earlier; yesterday's sales are a strong feature for today's

Features from time

Models do not understand timestamps directly. Typical features are calendar parts (hour, weekday, month), lags and rolling summaries:

python · try it yourself
import pandas as pd

sales = pd.DataFrame(
    {"units": [12, 15, 14, 30, 33, 11, 13, 16, 15, 31]},
    index=pd.date_range("2026-05-04", periods=10, freq="D"),
)
sales["weekday"] = sales.index.day_name().str[:3]
sales["is_weekend"] = sales.index.dayofweek >= 5
sales["lag_1"] = sales["units"].shift(1)
sales["mean_3d"] = sales["units"].rolling(3).mean().round(1)
print(sales)
            units weekday  is_weekend  lag_1  mean_3d
2026-05-04     12     Mon       False    NaN      NaN
2026-05-05     15     Tue       False   12.0      NaN
2026-05-06     14     Wed       False   15.0     13.7
2026-05-07     30     Thu       False   14.0     19.7
2026-05-08     33     Fri       False   30.0     25.7
2026-05-09     11     Sat        True   33.0     24.7
2026-05-10     13     Sun        True   11.0     19.0
2026-05-11     16     Mon       False   13.0     13.3
2026-05-12     15     Tue       False   16.0     14.7
2026-05-13     31     Wed       False   15.0     20.7

The first rows have NaN lags and rolling means: there is no earlier data. That is normal and must be handled (dropped or filled) before training.

Irregular events become regular series

Logs of events (a purchase, a login, a door opening) arrive at irregular times. Counting them per fixed window turns them into a regular series:

python · try it yourself
import pandas as pd

events = pd.to_datetime([
    "2026-05-04 08:03", "2026-05-04 08:41", "2026-05-04 09:15",
    "2026-05-04 11:02", "2026-05-04 11:09", "2026-05-04 11:58",
])
counts = pd.Series(1, index=events).resample("h").sum()
print(counts)
2026-05-04 08:00:00    2
2026-05-04 09:00:00    1
2026-05-04 10:00:00    0
2026-05-04 11:00:00    3
Freq: h, dtype: int64

Note the 10:00 row with 0 events: resampling also reveals gaps, which in sensor data often mean a broken device rather than a quiet hour.

Pitfalls

  • Random splits leak the future. If you shuffle a time series before splitting, the model trains on Wednesday and is tested on Tuesday, which it could never do in real use. Split by time. The leakage lab in Data Preparation shows how much a random split inflates the score.
  • Time zones and daylight saving. A day with a clock change has 23 or 25 hours. Store UTC, convert for display.
  • Mixed frequencies. Joining a daily table to an hourly one silently repeats or drops values; resample first.
  • Missing timestamps look like normal rows. Check that the index is complete (pd.date_range from start to end, then compare).

Practice

  1. A sensor should report every 10 minutes from 00:00 to 23:50. How many readings should one day have, and how would you find the missing ones?
Answer

24 × 6 = 144 readings. Build the expected index with pd.date_range("00:00", periods=144, freq="10min") for that date and use expected.difference(actual.index) to list the missing timestamps.

  1. Why is lag_1 a reasonable feature for forecasting tomorrow's sales, but the rolling mean centred on today (rolling(3, center=True)) is not?
Answer

A centred window uses tomorrow's value, which you will not know at prediction time. Every feature must use only information available at the moment of prediction.

Test yourself

What makes time series different from an ordinary table of independent rows?

  1. It always has more columns
  2. The order of the rows carries information
  3. It can only hold integers
  4. It never has missing values

You want to evaluate a sales forecasting model. Which split is right?

  1. A random 80/20 split
  2. Train on the earlier period, test on the later period
  3. Test on the training data
  4. Split by product colour

After resampling event logs to hourly counts, an hour shows 0. What should you check?

  1. Nothing, zero is always correct
  2. Whether it was truly quiet or the data source was down
  3. Whether pandas has a bug
  4. That the time zone is set to local time