Platform Engineering · Lesson 251

pandas for ML Data Preparation

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

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: how many rows does the merge produce?

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.

71,800rows after the merge
23,100extra rows

Inflated: some customers now appear several times in training

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

pandas for ML grows in four levels: DataFrames, cleaning and reshaping, leakage-safe features, and data pipelines at scale.

Basic — DataFrames

At the basic level you can load and explore a table.

  • pd.read_csv, head, info, describe, value_counts.
  • Selecting columns 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.

Intermediate — Cleaning and reshaping

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.

Advanced — Leakage-safe features

At the advanced level features use only what was known at prediction time.

  • A cut-off date per row; windows computed before it (merge_asof, filtered group-bys).
  • Time-based and group-based splits; statistics fitted on training data only.
  • Vectorised features; no row-wise apply.

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.

Master — Data pipelines at scale

At the master level preparation is reproducible and fast.

  • Preparation as code with tests on counts and ranges; data contracts with schemas.
  • Parquet, column pruning, and engines such as Polars or DuckDB when pandas is too slow or too big.
  • A feature store when many models share features online and offline.

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.

Go deeper

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")

One time it broke

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.

Timeline

  • Week 1A churn model reaches 0.94 AUC with a random split and features computed as of the export date.
  • Week 3In production it ranks customers barely better than the old rules. The retention team's calls go to the wrong customers.
  • Week 4Rebuilt with per-customer cut-offs and a time split: 0.81 offline and 0.79 live, which is useful and honest.

What changed after

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.

Python, example by example

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.

1. A DataFrame and its basics

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}

2. Read CSV text and select

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

3. Missing values

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']}

4. groupby and aggregate

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

5. Join two tables

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)

6. Feature engineering

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

7. Encode categories

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

8. Time series: resample and roll

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]

9. A train/test split without leakage

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]

Practice: write the program yourself

Write each one from scratch before you open the solution. The output under each solution is what it really prints.

  1. 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.

    Show a solution
    # 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}
  2. Make a DataFrame of 5 requests with a status column, and print the share of 5xx responses.

    Show a solution
    # 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
  3. Join pods (name, node) with nodes (node, zone) and print how many pods run in each zone.

    Show a solution
    # 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}
  4. One-hot encode the column env with values dev, prod, dev and print the column names.

    Show a solution
    # 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']

Try it yourself, from scratch

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.

1. Terminal: set up and run

Type each one, read what it prints, and compare it with the note above it.

  1. 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
  2. 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())"
  3. 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')"
  4. 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())"
  5. Clean up.

    rm -f c.csv p.csv m.csv

2. Python: join_and_split.py

This 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

3. What to notice

4. Advanced: a test that keeps the program honest

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Prepare a training set for predicting which support tickets will escalate, from tickets, customers, and agent events.

Clarifying questions to ask

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?

Rough sizing

Say 400,000 tickets over two years, 30,000 customers, 25 million agent events, and an escalation rate of 6%.

Shape of the answer

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.

Trade-offs to name

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.

Saved on this device, in this browser.
Next in this series · Lesson 252
scikit-learn: Pipelines, Cross-Validation, and Honest Evaluation

scikit-learn is the standard Python library for classic machine learning: one consistent fit/predict interface for preprocessing and models, joined into a Pipeline so the exact same steps run in training and in production.

Go to Lesson 252 →

Or browse the full course from the Lessons index.