Before any model trains, someone turns raw tables into a clean training set, and that is usually done in pandas: a DataFrame of named, typed columns with fast group-by, join, and time operations. Most model problems are data problems introduced here. This lesson prepares one churn dataset from three CSV files, through types, missing values, joins, group-bys, features, and the split, and shows the two mistakes that quietly ruin models: a join that duplicates rows, and a split that lets the future leak into training.
Difficulty: Intermediate · Know this first: Lesson 250, Lesson 37
This bar adds up minutes to prepare the training set, including what its mistakes cost. It is a worked example, not a measurement. The join and split hops are where data problems become model problems.
The left table has one row per customer. Set how many customers have more than one row on the right, and how many rows each of them has.
Inflated: some customers now appear several times in training
Three questions. No score is saved anywhere — this is just you against the material.
pandas for ML grows in four levels: DataFrames, cleaning and reshaping, leakage-safe features, and data pipelines at scale.
At the basic level you can load and explore a table.
pd.read_csv, head, info, describe, value_counts.df["a"], rows df.loc[mask], sorting sort_values.to_csv, to_parquet.Where it breaks: IDs read as numbers lose leading zeros and become floats when a value is missing.
Try it: Basic
A customer_id column shows 1.2345e+05 and lost its leading zeros. What fixes it?
Now do it: Reload a CSV with explicit dtypes and compare df.dtypes.
At the intermediate level you shape data correctly.
to_numeric(errors="coerce"), to_datetime, astype("category").groupby().agg() with named aggregations; pivot_table; melt.merge(..., validate=, indicator=True) and row-count checks.Try it: Intermediate
What does indicator=True add to a merge?
Now do it: Merge two tables with indicator=True and count each _merge value.
At the advanced level features use only what was known at prediction time.
merge_asof, filtered group-bys).Try it: Advanced
A feature "days since last login" is computed as of the data export date for every customer. What is wrong?
Now do it: List each feature in a model you know and its "as of" date.
At the master level preparation is reproducible and fast.
Trade-off: notebooks are fast to explore and hard to reproduce; scripted pipelines with tests are slower to start and the only thing you can trust in production.
Try it: Master
A pandas job takes 2 hours and 60 GB of memory on 200 million rows. What is a good next step?
Now do it: Run one group-by from a pandas job in DuckDB on the same Parquet file and compare the time.
The preparation as a script with checks at every step. Install with pip install pandas pyarrow.
import numpy as np, pandas as pd
cust = pd.read_csv("customers.csv", dtype={"customer_id": "string"}, parse_dates=["signup", "cutoff"])
plans = pd.read_csv("plans.csv", dtype={"customer_id": "string"}, parse_dates=["changed"])
events = pd.read_csv("events.csv", dtype={"customer_id": "string"}, parse_dates=["ts"])
assert cust["customer_id"].is_unique
latest = plans.sort_values("changed").drop_duplicates("customer_id", keep="last")
df = cust.merge(latest, on="customer_id", how="left", validate="one_to_one")
assert len(df) == len(cust), "merge changed the row count"
# events in the 30 days before each customer's own cut-off
ev = events.merge(cust[["customer_id", "cutoff"]], on="customer_id")
ev = ev[(ev["ts"] < ev["cutoff"]) & (ev["ts"] >= ev["cutoff"] - pd.Timedelta(days=30))]
logins = ev[ev["type"] == "login"].groupby("customer_id").size().rename("logins_30d")
df = df.merge(logins, on="customer_id", how="left").fillna({"logins_30d": 0})
df["tenure_days"] = (df["cutoff"] - df["signup"]).dt.days
df["log_mrr"] = np.log1p(pd.to_numeric(df["mrr"], errors="coerce"))
train = df[df["cutoff"] < "2026-09-01"]
test = df[df["cutoff"] >= "2026-09-01"]
assert train["cutoff"].max() < test["cutoff"].min()
print(len(train), "train rows,", len(test), "test rows")
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A model was promoted on a score that measured a leak.
Every dataset records each row's cut-off date, features are computed relative to it, splits are by time by default, and offline-versus-live gaps above a threshold block promotion.
pandas turns tables into DataFrames you can filter, clean, join, and reshape: most of the work before any model is trained. Each example is a whole program: save it under the name in its first line, run it with python3, and you should see exactly the output below it.
Before you start: These examples need pandas: make a virtual environment and install them with python3 -m venv .venv && . .venv/bin/activate && pip install pandas. Versions differ in small ways, so a number in the last decimal place may not match yours.
Rows and named columns; each column has a type. describe() summarises the numbers.
# example_01.py
import pandas as pd
df = pd.DataFrame({"service": ["api", "web", "api", "db"], "ms": [120, 95, 410, 30], "ok": [True, True, False, True]})
print(df)
print({col: str(t) for col, t in df.dtypes.items()})
print(df["ms"].describe().round(1).to_dict())
$ python3 example_01.py
service ms ok
0 api 120 True
1 web 95 True
2 api 410 False
3 db 30 True
{'service': 'str', 'ms': 'int64', 'ok': 'bool'}
{'count': 4.0, 'mean': 163.8, 'std': 168.5, 'min': 30.0, '25%': 78.8, '50%': 107.5, '75%': 192.5, 'max': 410.0}
read_csv parses types for you; select columns by name and rows by condition.
# example_02.py import io import pandas as pd csv = "ts,service,ms,status\n2026-11-03 10:00,api,120,200\n2026-11-03 10:01,web,95,200\n2026-11-03 10:02,api,2310,502\n2026-11-03 10:03,api,140,200\n" df = pd.read_csv(io.StringIO(csv), parse_dates=["ts"]) print(df[["service", "ms"]].head(2)) print(df[(df.service == "api") & (df.status >= 500)]) print(df.loc[df.ms.idxmax(), "ts"])
$ python3 example_02.py
service ms
0 api 120
1 web 95
ts service ms status
2 2026-11-03 10:02:00 api 2310 502
2026-11-03 10:02:00
Find them, then drop or fill them on purpose; never let a model see NaN by accident.
# example_03.py
import numpy as np
import pandas as pd
df = pd.DataFrame({"cpu": [40, np.nan, 90, 55], "team": ["sre", None, "dev", "sre"]})
print(df.isna().sum().to_dict())
print(df.dropna().shape, df.fillna({"cpu": df.cpu.median(), "team": "unknown"}).to_dict("list"))
$ python3 example_03.py
{'cpu': 1, 'team': 1}
(3, 2) {'cpu': [40.0, 55.0, 90.0, 55.0], 'team': ['sre', 'unknown', 'dev', 'sre']}
Split by a key, compute per group, combine: the most-used pandas pattern.
# example_04.py
import pandas as pd
df = pd.DataFrame({"svc": ["api", "api", "web", "web", "api"], "ms": [120, 140, 95, 101, 2310], "err": [0, 0, 0, 1, 1]})
print(df.groupby("svc").agg(n=("ms", "size"), p50=("ms", "median"), mean_ms=("ms", "mean"), errors=("err", "sum")))
$ python3 example_04.py
n p50 mean_ms errors
svc
api 3 140.0 856.666667 1
web 2 98.0 98.000000 1
merge is SQL's JOIN: here, add each service's owning team.
# example_05.py
import pandas as pd
calls = pd.DataFrame({"svc": ["api", "web", "batch"], "cost": [300, 120, 40]})
owners = pd.DataFrame({"svc": ["api", "web"], "team": ["payments", "frontend"]})
print(calls.merge(owners, on="svc", how="left"))
print(calls.merge(owners, on="svc", how="inner").shape)
$ python3 example_05.py
svc cost team
0 api 300 payments
1 web 120 frontend
2 batch 40 NaN
(2, 3)
New columns from old ones: ratios, flags, date parts, and buckets.
# example_06.py
import pandas as pd
df = pd.DataFrame({"ts": pd.to_datetime(["2026-11-02 09:00", "2026-11-03 23:30", "2026-11-07 14:00"]), "req": [1200, 300, 800], "err": [12, 30, 0]})
df["err_rate"] = (df.err / df.req).round(3)
df["weekend"] = df.ts.dt.dayofweek >= 5
df["hour"] = df.ts.dt.hour
df["load"] = pd.cut(df.req, bins=[0, 500, 1000, 10_000], labels=["low", "mid", "high"])
print(df.drop(columns="ts"))
$ python3 example_06.py
req err err_rate weekend hour load
0 1200 12 0.01 False 9 high
1 300 30 0.10 False 23 low
2 800 0 0.00 True 14 mid
Models need numbers: one-hot encode text categories into 0/1 columns.
# example_07.py
import pandas as pd
df = pd.DataFrame({"region": ["eu", "us", "eu", "ap"], "tier": ["gold", "free", "free", "gold"]})
print(pd.get_dummies(df, columns=["region", "tier"], dtype=int))
$ python3 example_07.py region_ap region_eu region_us tier_free tier_gold 0 0 1 0 0 1 1 0 0 1 1 0 2 0 1 0 1 0 3 1 0 0 0 1
Put events into fixed time buckets, then smooth with a rolling window.
# example_08.py
import pandas as pd
idx = pd.date_range("2026-11-03 10:00", periods=8, freq="30s")
s = pd.Series([1, 3, 2, 8, 9, 2, 1, 4], index=idx)
print(s.resample("1min").sum().to_dict())
print(s.rolling(3).mean().round(2).tolist())
$ python3 example_08.py
{Timestamp('2026-11-03 10:00:00'): 4, Timestamp('2026-11-03 10:01:00'): 10, Timestamp('2026-11-03 10:02:00'): 11, Timestamp('2026-11-03 10:03:00'): 5}
[nan, nan, 2.0, 4.33, 6.33, 6.33, 4.0, 2.33]
Split by time for time-ordered data, and compute any scaling from the training part only.
# example_09.py
import pandas as pd
df = pd.DataFrame({"day": range(1, 11), "x": [10, 12, 11, 13, 15, 14, 16, 18, 17, 19]})
train, test = df[df.day <= 7], df[df.day > 7]
mu, sd = train.x.mean(), train.x.std()
print(len(train), len(test), round(mu, 3), round(sd, 3))
print(((test.x - mu) / sd).round(3).tolist())
$ python3 example_09.py 7 3 13.0 2.16 [2.315, 1.852, 2.777]
Write each one from scratch before you open the solution. The output under each solution is what it really prints.
From {"host": ["a", "b", "a", "c"], "cpu": [50, 90, 70, None]}, fill the missing CPU with the mean and print the mean CPU per host.
# task_1.py
import pandas as pd
df = pd.DataFrame({"host": ["a", "b", "a", "c"], "cpu": [50, 90, 70, None]})
df["cpu"] = df.cpu.fillna(df.cpu.mean())
print(df.groupby("host").cpu.mean().to_dict())$ python3 task_1.py
{'a': 60.0, 'b': 90.0, 'c': 70.0}Make a DataFrame of 5 requests with a status column, and print the share of 5xx responses.
# task_2.py
import pandas as pd
df = pd.DataFrame({"status": [200, 502, 200, 503, 200]})
print((df.status >= 500).mean())$ python3 task_2.py 0.4
Join pods (name, node) with nodes (node, zone) and print how many pods run in each zone.
# task_3.py
import pandas as pd
pods = pd.DataFrame({"name": ["p1", "p2", "p3"], "node": ["n1", "n2", "n1"]})
nodes = pd.DataFrame({"node": ["n1", "n2"], "zone": ["eu-1a", "eu-1b"]})
print(pods.merge(nodes, on="node").groupby("zone").size().to_dict())$ python3 task_3.py
{'eu-1a': 2, 'eu-1b': 1}One-hot encode the column env with values dev, prod, dev and print the column names.
# task_4.py
import pandas as pd
print(list(pd.get_dummies(pd.DataFrame({"env": ["dev", "prod", "dev"]}), dtype=int).columns))$ python3 task_4.py ['env_dev', 'env_prod']
You need Python 3 on Linux, macOS, or WSL on Windows (run wsl --install in PowerShell once); check with python3 --version. The terminal is only for setting Python up and running it and its tools: the Python itself goes in .py files, in part 2 and in "Python, example by example" above.
Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install pandas for the commands.
Type each one, read what it prints, and compare it with the note above it.
Make a folder for this lesson with its own virtual environment, and install what the lesson needs into it. Every command after this runs inside it; deactivate leaves it, and source .venv/bin/activate brings it back.
mkdir -p ~/labs/pandas-for-ml-data-preparation && cd ~/labs/pandas-for-ml-data-preparation python3 -m venv .venv || echo "No venv module: on Debian or Ubuntu run sudo apt install -y python3-venv and try again" source .venv/bin/activate && python --version pip install pandas
IDs read as numbers lose their leading zeros.
printf "customer_id,mrr\n00042,10\n00107,20\n" > c.csv
python -c "import pandas as pd; print(pd.read_csv('c.csv').customer_id.tolist(), pd.read_csv('c.csv', dtype={'customer_id': 'string'}).customer_id.tolist())"A join on a duplicated key multiplies rows.
printf "customer_id,plan\n00042,basic\n00042,pro\n00107,basic\n" > p.csv
python -c "import pandas as pd; c = pd.read_csv('c.csv', dtype=str); p = pd.read_csv('p.csv', dtype=str); print(len(c), 'customers ->', len(c.merge(p, on='customer_id')), 'rows')"Share of missing values per column.
printf "a,b\n1,\n,2\n3,4\n" > m.csv
python -c "import pandas as pd; print(pd.read_csv('m.csv').isna().mean())"Clean up.
rm -f c.csv p.csv m.csv
join_and_split.pyThis program reproduces the two data-preparation mistakes with plain Python: a join on a non-unique key that multiplies rows, and a random split on time-ordered data that puts future rows into training. Save it as join_and_split.py in the lesson folder, then run it.
# join_and_split.py
import random
from collections import Counter
customers = [f"c{i:03d}" for i in range(10)]
plans = [(c, "basic") for c in customers] + [("c003", "pro"), ("c003", "team"), ("c007", "pro")]
joined = [(c, p) for c in customers for pc, p in plans if pc == c]
dupes = {c: n for c, n in Counter(c for c, _ in joined).items() if n > 1}
print(f"{len(customers)} customers joined to plans -> {len(joined)} rows; duplicated: {dupes}")
rows = [(month, f"r{month}-{i}") for month in range(1, 13) for i in range(5)] # 12 months of rows
random.seed(3)
shuffled = rows[:]
random.shuffle(shuffled)
train_r, test_r = shuffled[:48], shuffled[48:]
leak = sum(1 for m, _ in train_r if m > min(m for m, _ in test_r))
print(f"random split: test months {sorted({m for m, _ in test_r})}; {leak} training rows are later than the earliest test row")
train_t = [r for r in rows if r[0] <= 10]
test_t = [r for r in rows if r[0] > 10]
print(f"time split: train months 1-{max(m for m, _ in train_t)}, test months {min(m for m, _ in test_t)}-12; leaked rows 0")
Run it, and you should see this output:
$ python3 join_and_split.py
10 customers joined to plans -> 13 rows; duplicated: {'c003': 3, 'c007': 2}
random split: test months [1, 2, 4, 5, 7, 8, 9, 11, 12]; 45 training rows are later than the earliest test row
time split: train months 1-10, test months 11-12; leaked rows 0
A program you keep needs a test, so you know at once when a change alters what it does. This one uses unittest, which comes with Python: it runs join_and_split.py and checks that it exits cleanly and prints exactly the output above. Save it as test_join_and_split.py next to the program.
# test_join_and_split.py: checks that join_and_split.py still prints exactly what this lesson shows.
# Run it with: python3 -m unittest -v test_join_and_split
import subprocess
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
EXPECTED = r"""
10 customers joined to plans -> 13 rows; duplicated: {'c003': 3, 'c007': 2}
random split: test months [1, 2, 4, 5, 7, 8, 9, 11, 12]; 45 training rows are later than the earliest test row
time split: train months 1-10, test months 11-12; leaked rows 0
""".strip("\n")
class TestJoinAndSplit(unittest.TestCase):
def run_program(self):
return subprocess.run([sys.executable, str(HERE / "join_and_split.py")], cwd=HERE,
capture_output=True, text=True, timeout=60)
def test_exits_cleanly(self):
result = self.run_program()
self.assertEqual(result.returncode, 0, result.stderr)
def test_prints_the_expected_output(self):
result = self.run_program()
self.assertEqual(result.stdout.rstrip(), EXPECTED)
if __name__ == "__main__":
unittest.main()
Run it: you should see both tests end in ok, then OK. Then change one value in the program, run it again, and read how the failure shows you the difference. pytest runs the same file unchanged, if you prefer it.
python3 -m unittest -v test_join_and_split
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, rm, echo, cd, Pipes, Redirection, If...Else.Prepare a training set for predicting which support tickets will escalate, from tickets, customers, and agent events.
What is each row, and what is its cut-off time? Which joins could duplicate rows? Which features could leak the outcome? How do you split?
Say 400,000 tickets over two years, 30,000 customers, 25 million agent events, and an escalation rate of 6%.
One row per ticket, cut-off at 1 hour after creation; customers joined many_to_one with validate; agent events filtered to before the cut-off and aggregated per ticket; no features from fields filled in later (resolution, final priority); train on the first 20 months, test on the last 4; a check that train ends before test begins.
An early cut-off makes predictions useful and features weaker; a later one is more accurate and less actionable. A time split is honest and leaves less recent data for training.