Worked Example: Features from Timestamps, Text and Group Aggregates
Build cyclical time features, TF-IDF note features and a sender history computed only from outcomes known at booking time, then keep each one only if its cross-validated gain is larger than the fold-to-fold spread.
Contentsand lesson path
On this page
- The problem
- Step 1: A baseline to beat
- Step 2: Features from the timestamp
- Step 3: Features from free text
- Step 4: Group aggregates from the past only
- Step 5: Keep what the folds support
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Preparation & Feature Engineering
- Auditing Raw Data Before You Model Concept · 20 min
- Imputation, Encoding and Scaling, Chosen by Model Family Concept · 25 min
- Worked Example: Features from Timestamps, Text and Group Aggregates Worked example · 25 min
- Lab: One Pipeline from Raw Rows to Predictions Lab · 30 min
- Worked Example: Building a Point-in-Time-Correct Training Set Worked example · 20 min
- Check: Preparing Data the Same Way Twice Knowledge check · 8 questions
What you will learn
- Engineer features from dates, free text and group aggregates computed only from data available at each prediction time (point-in-time-correct as-of joins), and keep only those that improve cross-validated scores.
01. The problem
The courier from lesson 1 now has a cleaned table of 6,000 bookings from January to May 2026: booking time, sender, depot, distance, a free-text delivery note, and whether the parcel arrived late. Distance and depot alone predict lateness poorly. Which features can be built from the timestamp, the note and the sender's history, using only information available at booking time, and which of them actually improve the cross-validated score?
Three rules guide every step:
- a feature for a row may use only what was known when that row's prediction is made;
- anything that learns from data, such as a vocabulary or a scaler, is fitted inside cross-validation, never before it;
- a feature stays only if its gain is larger than the noise between folds.
The script below writes the data, with hidden effects to find: late-evening bookings, a Saturday effect, some note phrases, and senders with poor addresses. Tested with Python 3.12, NumPy 2.5, pandas 3.1 and scikit-learn 1.9; run every script in the same folder.
"""Write parcels.csv: 6,000 cleaned parcel bookings with time, text and sender."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 6_000
NOTES = [ # (text, effect on the log-odds of a late delivery)
("", 0.0), ("", 0.0), ("", 0.0),
("Please call on arrival", 0.9), ("Calling ahead is needed", 0.9),
("Customer called about access", 0.9), ("Gate code 4417 at the side door", 0.7),
("Leave in the porch if out", -0.6), ("Leave safe behind the bins", -0.6),
("Fragile glass, handle with care", 0.2), ("Deliver to reception", 0.0),
]
start = pd.Timestamp("2026-01-05")
booked = start + pd.to_timedelta(rng.integers(0, 120 * 24 * 60, n), unit="min")
sender = rng.integers(0, 600, n)
quality = rng.normal(0, 0.9, 600) # some senders give poor addresses
depot = rng.choice([f"D{i:02d}" for i in range(12)], n)
note_i = rng.integers(0, len(NOTES), n)
distance = rng.gamma(2.0, 9.0, n).round(1)
hour = booked.hour + booked.minute / 60
logit = (-2.0 + 0.03 * distance + quality[sender]
+ 1.0 * np.cos(2 * np.pi * (hour - 23) / 24) # late-evening bookings
+ 0.5 * (booked.day_of_week == 5) # Saturday
+ np.array([NOTES[i][1] for i in note_i]))
late = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df = pd.DataFrame({
"parcel_id": [f"P{i:05d}" for i in range(n)],
"booked_at": booked, "sender_id": [f"S{s:03d}" for s in sender],
"depot": depot, "distance_km": distance,
"note": [NOTES[i][0] for i in note_i], "late": late,
}).sort_values("booked_at", ignore_index=True)
df.to_csv("parcels.csv", index=False)
print(df.shape, "| late share", round(df["late"].mean(), 3))
print(df.head(3)[["booked_at", "sender_id", "note", "late"]].to_string())(6000, 7) | late share 0.299
booked_at sender_id note late
0 2026-01-05 00:00:00 S398 Leave safe behind the bins 1
1 2026-01-05 01:29:00 S042 1
2 2026-01-05 01:38:00 S044 Calling ahead is needed 0pandas reads empty notes back as NaN, so the loader below fills them with ''. The helper scores a feature set with one fixed logistic regression, so only the features change between runs. It uses TimeSeriesSplit: the rows are sorted by booking time, and each fold trains on earlier bookings and validates on the next block of later ones, as production would.
"""Shared helpers: load the data and score one feature set with the same folds."""
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
FOLDS = TimeSeriesSplit(n_splits=5) # rows are sorted by booked_at: train on the past
def load() -> pd.DataFrame:
df = pd.read_csv("parcels.csv", parse_dates=["booked_at"])
df["note"] = df["note"].fillna("") # empty notes come back from CSV as NaN
return df
def cv_auc(df, numeric, categorical=(), text=None):
"""Five AUC scores, one per fold, for a logistic regression on these columns."""
parts = [("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True),
StandardScaler()), list(numeric))]
if categorical:
parts.append(("cat", OneHotEncoder(handle_unknown="ignore"), list(categorical)))
if text:
parts.append(("txt", TfidfVectorizer(min_df=5), text)) # one column name
model = make_pipeline(ColumnTransformer(parts), LogisticRegression(max_iter=2000))
return cross_val_score(model, df, df["late"], cv=FOLDS, scoring="roc_auc")
def show(name, scores):
print(f"{name:<22} AUC {scores.mean():.3f} ± {scores.std():.3f} folds",
" ".join(f"{s:.3f}" for s in scores))02. Step 1: A baseline to beat
from cv_tools import cv_auc, load, show
df = load()
print(df.dtypes.to_string())
base = cv_auc(df, numeric=["distance_km"], categorical=["depot"])
show("baseline", base)parcel_id str
booked_at datetime64[us]
sender_id str
depot str
distance_km float64
note str
late int64
baseline AUC 0.583 ± 0.022 folds 0.543 0.582 0.593 0.587 0.610pandas 3 parses booked_at to datetime64[us] and reads the text columns as str. The baseline, distance plus a one-hot depot, reaches an AUC of 0.583. Later scores use the same five folds.
03. Step 2: Features from the timestamp
To a model, a timestamp is one number, the time since some origin, which says little. Its parts say more: hour of day, day of week, month, public holidays. Extracting them is a row-by-row calculation that learns nothing from other rows, so it can safely happen before cross-validation.
The hour needs care. As a raw number it puts 23:00 and 01:00 22 units apart, although they are two hours apart on the clock. A linear model given the raw hour can only make lateness rise or fall steadily through the day; it cannot say "late evening and just after midnight are bad". Cyclical encoding places the hour on a circle with two features, sin(2πh/24) and cos(2πh/24), so that 23:00 and 01:00 get nearly the same pair.
import numpy as np
import pandas as pd
from cv_tools import cv_auc, load, show
def add_date_parts(df: pd.DataFrame) -> pd.DataFrame:
"""Row-by-row features from booked_at: nothing is learned from other rows."""
t = df["booked_at"]
hour = t.dt.hour + t.dt.minute / 60
return df.assign(
hour=hour,
hour_sin=np.sin(2 * np.pi * hour / 24),
hour_cos=np.cos(2 * np.pi * hour / 24),
weekday=t.dt.day_name(),
day_of_month=t.dt.day,
)
if __name__ == "__main__":
df = add_date_parts(load())
demo = pd.DataFrame({"booked_at": pd.to_datetime(["2026-02-02 23:00",
"2026-02-03 01:00"])})
print(add_date_parts(demo)[["hour", "hour_sin", "hour_cos"]].round(3))
base = cv_auc(df, ["distance_km"], ["depot"])
show("baseline", base)
show("+ raw hour", cv_auc(df, ["distance_km", "hour"], ["depot"]))
cyc = ["distance_km", "hour_sin", "hour_cos"]
show("+ hour sin/cos", cv_auc(df, cyc, ["depot"]))
show("+ sin/cos + weekday", cv_auc(df, cyc, ["depot", "weekday"]))
show("+ day of month", cv_auc(df, ["distance_km", "day_of_month"], ["depot"])) hour hour_sin hour_cos
0 23.0 -0.259 0.966
1 1.0 0.259 0.966
baseline AUC 0.583 ± 0.022 folds 0.543 0.582 0.593 0.587 0.610
+ raw hour AUC 0.592 ± 0.022 folds 0.553 0.595 0.592 0.606 0.617
+ hour sin/cos AUC 0.681 ± 0.015 folds 0.654 0.695 0.685 0.675 0.695
+ sin/cos + weekday AUC 0.680 ± 0.011 folds 0.661 0.676 0.685 0.683 0.694
+ day of month AUC 0.581 ± 0.022 folds 0.539 0.582 0.592 0.594 0.597The demo gives 23:00 and 01:00 the same cosine and mirrored sines. The raw hour barely moves the baseline (0.583 to 0.592); the sine and cosine pair lifts it to 0.681. One-hot weekday adds nothing measurable, and the day of the month is noise. Weekly or yearly cycles use periods of 7 or 365.25 days. One pandas 3.1 detail: use dt.day_of_week, because dayofweek now raises a deprecation warning.
04. Step 3: Features from free text
Free text becomes features through a bag of words: each document becomes a vector of word counts, ignoring word order. TF-IDF (term frequency times inverse document frequency) reweights the counts so that a word found in many documents, such as "the", counts for less than a rarer, more specific one. TfidfVectorizer lowercases the text, splits it into tokens of two or more letters or digits, builds a vocabulary and, with min_df=5, drops terms found in fewer than five notes. The vocabulary and the weights are learned from data, so the vectorizer sits inside the pipeline that cross-validation refits.
import re
import textwrap
from sklearn.feature_extraction.text import TfidfVectorizer
from cv_tools import cv_auc, load, show
from step2_dates import add_date_parts
df = add_date_parts(load())
notes = df["note"]
tfidf = TfidfVectorizer(min_df=5).fit(notes) # lowercases and splits on words
print(textwrap.fill(f"{len(tfidf.vocabulary_)} terms: "
+ " ".join(sorted(tfidf.vocabulary_)), 80))
def crude_stem(text: str) -> list[str]:
"""A toy suffix stripper: it shows the idea, use a real stemmer in practice."""
words = re.findall(r"[a-z]{2,}", text.lower())
return [re.sub(r"(ing|ed|s)$", "", w) if len(w) > 4 else w for w in words]
stemmed = TfidfVectorizer(tokenizer=crude_stem, token_pattern=None, min_df=5)
stemmed.fit(notes)
print(textwrap.fill(f"{len(stemmed.vocabulary_)} terms: "
+ " ".join(sorted(stemmed.vocabulary_)), 80))
idf = dict(zip(tfidf.get_feature_names_out(), tfidf.idf_.round(2)))
print("idf:", {t: float(idf[t]) for t in ["the", "leave", "call", "fragile"]})
num = ["distance_km", "hour_sin", "hour_cos"]
show("dates", cv_auc(df, num, ["depot", "weekday"]))
show("dates + note TF-IDF", cv_auc(df, num, ["depot", "weekday"], text="note"))35 terms: 4417 about access ahead arrival at behind bins call called calling
care code customer deliver door fragile gate glass handle if in is leave needed
on out please porch reception safe side the to with
32 terms: about acces ahead arrival at behind bins call care code customer
deliver door fragile gate glas handle if in is leave need on out please porch
reception safe side the to with
idf: {'the': 2.28, 'leave': 2.66, 'call': 3.38, 'fragile': 3.42}
dates AUC 0.680 ± 0.011 folds 0.661 0.676 0.685 0.683 0.694
dates + note TF-IDF AUC 0.713 ± 0.019 folds 0.680 0.720 0.706 0.722 0.738The IDF weights show the reweighting: "the" appears in many notes and gets 2.28, "fragile" in few and gets 3.42.
Three terms, call, called and calling, are one idea in three spellings. Text normalisation reduces such variation before counting. Lowercasing and stop-word removal (dropping words like "the" with stop_words='english') are built in. Stemming cuts words to a stem with suffix rules, quickly and crudely: the toy stemmer merges the three forms of "call", but it also turns "glass" into "glas" and "access" into "acces". Real stemmers, such as Porter and Snowball in the NLTK library, use more rules but share the crudeness. Lemmatisation maps each word to its dictionary form, its lemma, using a vocabulary and often the part of speech, so "called" becomes "call" and "better" can become "good". It is slower and needs a dictionary or language model, such as spaCy or NLTK's WordNet lemmatiser. Both plug into TfidfVectorizer through its tokenizer argument, as the toy does. For short, repetitive notes, normalisation changes little.
Adding the TF-IDF features lifts the AUC from 0.680 to 0.713.
05. Step 4: Group aggregates from the past only
A group aggregate summarises other rows of the same group: a sender's past late rate, a depot's parcel count last week. They carry history the single row lacks, and they are the easiest place to leak the future. The wrong version below, groupby(...).transform("mean") over the whole table, gives every parcel its sender's late rate over all their parcels: past, future and the parcel itself.
The correct version uses past rows only, and only outcomes already known. A parcel's lateness is known about two days after booking, once delivered. So each outcome gets a known_at time, cumulative counts per sender are taken in known_at order, and pd.merge_asof attaches to each booking the latest counts with known_at strictly before booked_at. An as-of join matches on the nearest earlier key rather than an equal one; lesson 6 treats it in depth.
import pandas as pd
from cv_tools import cv_auc, load, show
from step2_dates import add_date_parts
def add_sender_history(df: pd.DataFrame) -> pd.DataFrame:
"""Sender late rate from outcomes known before booking (known 2 days later)."""
known = df[["sender_id", "booked_at", "late"]].assign(
known_at=df["booked_at"] + pd.Timedelta(days=2)).sort_values("known_at")
by_sender = known.groupby("sender_id")
known["n_known"] = by_sender.cumcount() + 1
known["late_known"] = by_sender["late"].cumsum()
out = pd.merge_asof(df, known[["sender_id", "known_at", "n_known", "late_known"]],
left_on="booked_at", right_on="known_at", by="sender_id",
direction="backward", allow_exact_matches=False)
out["n_known"] = out["n_known"].fillna(0).astype(int)
out["sender_rate_past"] = out["late_known"] / out["n_known"] # NaN: no history
return out.drop(columns=["known_at", "late_known"])
if __name__ == "__main__":
df = add_sender_history(add_date_parts(load())) # rows sorted by booked_at
# Wrong: one rate per sender over the whole table, this and later rows included
df["sender_rate_all"] = df.groupby("sender_id")["late"].transform("mean")
cols = ["booked_at", "late", "sender_rate_all", "n_known", "sender_rate_past"]
one = df.loc[df["sender_id"] == "S097", cols]
one = one.round({"sender_rate_all": 2, "sender_rate_past": 2})
print(one.to_string(index=False))
num, cat = ["distance_km", "hour_sin", "hour_cos"], ["depot", "weekday"]
show("dates + text", cv_auc(df, num, cat, text="note"))
show("+ sender rate, all", cv_auc(df, num + ["sender_rate_all"], cat, text="note"))
show("+ sender rate, past",
cv_auc(df, num + ["n_known", "sender_rate_past"], cat, text="note")) booked_at late sender_rate_all n_known sender_rate_past
2026-01-24 07:02:00 0 0.5 0 NaN
2026-02-11 17:35:00 0 0.5 1 0.0
2026-03-12 06:13:00 0 0.5 2 0.0
2026-03-14 22:07:00 1 0.5 3 0.0
2026-03-16 02:12:00 1 0.5 3 0.0
2026-03-28 16:33:00 1 0.5 5 0.4
dates + text AUC 0.713 ± 0.019 folds 0.680 0.720 0.706 0.722 0.738
+ sender rate, all AUC 0.839 ± 0.013 folds 0.819 0.832 0.852 0.839 0.853
+ sender rate, past AUC 0.741 ± 0.024 folds 0.699 0.741 0.739 0.749 0.775Sender S097 shows the difference. The whole-table rate is 0.5 on every row, even the first, when nothing was known about this sender. The past rate starts empty (NaN, which the imputer fills and flags), and the parcel booked on 16 March still counts only three known outcomes, because the one booked on 14 March has not been delivered yet.
The whole-table rate lifts the AUC from 0.713 to 0.839, a gain that cannot survive production, where future outcomes are unknown. The honest rate gives 0.741. A jump far beyond anything else you tried is a reason for suspicion.
06. Step 5: Keep what the folds support
Each candidate now gets a decision. A higher mean alone is not evidence: scores vary between folds, and a small gain may be noise. Two habits make the comparison fair. Score every candidate on the same folds, so the gain can be measured fold by fold, a paired comparison. Then compare the mean gain with its spread: with five folds, a gain smaller than the standard deviation of the per-fold gains is too small to tell apart from noise. The script adds candidates one at a time to the set kept so far.
from cv_tools import cv_auc, load
from step2_dates import add_date_parts
from step4_history import add_sender_history
df = add_sender_history(add_date_parts(load()))
num, cat, text = ["distance_km"], ["depot"], None
current = cv_auc(df, num, cat)
candidates = [ # (name, numeric, categorical, text) to add on top of what is kept
("hour sin/cos", ["hour_sin", "hour_cos"], [], None),
("day of month", ["day_of_month"], [], None),
("weekday", [], ["weekday"], None),
("note TF-IDF", [], [], "note"),
("sender history", ["n_known", "sender_rate_past"], [], None),
]
print(f"{'candidate':<15} {'mean gain':>9} {'sd of gain':>10} {'folds up':>8}"
" decision")
for name, n_add, c_add, t_add in candidates:
scores = cv_auc(df, num + n_add, cat + c_add, text=t_add or text)
gain = scores - current # paired: the same five folds both times
keep = gain.mean() > gain.std(ddof=1) # gain larger than its own spread
print(f"{name:<15} {gain.mean():>+9.3f} {gain.std(ddof=1):>10.3f} "
f"{(gain > 0).sum():>6}/5 {'keep' if keep else 'drop'}")
if keep:
num, cat, text, current = num + n_add, cat + c_add, t_add or text, scores
print("kept:", ", ".join(num + cat + ([text] if text else [])))
print(f"final CV AUC {current.mean():.3f} ± {current.std():.3f}")candidate mean gain sd of gain folds up decision
hour sin/cos +0.098 0.013 5/5 keep
day of month -0.001 0.003 2/5 drop
weekday -0.001 0.011 2/5 drop
note TF-IDF +0.032 0.012 5/5 keep
sender history +0.027 0.007 5/5 keep
kept: distance_km, hour_sin, hour_cos, n_known, sender_rate_past, depot, note
final CV AUC 0.741 ± 0.028The hour pair, the note and the sender history pass, each improving all five folds. The day of the month fails, and so does the weekday, although the generator built in a Saturday effect: it is too small to detect in 6,000 rows, so it costs a column for no measurable return. "Drop" here means "not shown to help", not "proven useless". Cost counts too: a feature that needs a slow lookup must earn more than a free one.
This one-at-a-time procedure is a simple form of feature selection. scikit-learn automates others, such as SequentialFeatureSelector, SelectFromModel with an L1-penalised model, and SelectKBest. Selection learns from the labels, so it must run inside cross-validation; choosing features on all the data and then cross-validating the chosen set reports an optimistic score. Keep the test set out of these decisions.
07. Common mistakes
08. Check your understanding
09. Apply it
Continue the practice project on your mixed-type dataset.
- Add at least two engineered features: one from a datetime column (with cyclical encoding where the pattern wraps around) and one group aggregate computed only from rows known before each prediction time. If your data has a text column, add TF-IDF features as a third.
- Write a comparison like
step5_decide.py: the same folds for every candidate, the mean and standard deviation of the per-fold gain, and a keep or drop decision for each. - Compute the same aggregate the wrong way, over the whole table, and record how far it inflates the score: a measured example of leakage.
10. Review prompt
Without looking back, answer in your own words:
- Why does a linear model need sine and cosine features for the hour rather than the hour itself?
- What does IDF do to a word that appears in almost every document?
- How do stemming and lemmatisation differ, and what does each cost?
- Which two conditions must a group aggregate meet to be point-in-time correct?
- Why is a paired, per-fold comparison a better test of a new feature than two mean scores?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.