AI from scratch · Toolkit 2 · Stage 4: the engineer's toolkit
pandas and scikit-learn
Stage 3 used pandas and scikit-learn a line at a time. This lesson is the working kit: how a real table gets loaded, looked at, cleaned, grouped, joined and turned into features, and how scikit-learn's few rules let you swap any model into the same pipeline and tune it honestly. The table is real: every NYC subway elevator and escalator outage this site's archive saw in five weeks of fall 2026, 667 of them.
Data: MTA elevator and escalator outage feed, archived by ihor.sh, September 9 to October 15, 2026 (times in New York time). last_seen is the last time the feed listed the outage; for finished ones, that's when it ended, give or take the archive's polling interval.
1. Load it, then look before doing anything
pd.read_csv reads the file; parse_dates turns the time columns into real dates instead of text. Then four looks that catch most surprises: the first rows, the types and missing values, the numbers summarized, and how often each category appears.
The oldest outage started in September 2024, two years before the archive did. What's the most likely story?
- A parsing bug
- Long-running capital replacements: the feed still lists escalators that have been out for two years
- The archive is broken
Before any model: shape, types, missing values, ranges and category counts; the surprises live there.
2. Select, filter and add columns
| You want | pandas |
|---|---|
| Some columns | df[["station", "reason"]] |
| Rows where something is true | df[df["kind"] == "EL"], combined with & and | (each condition in brackets) |
| Rows and columns by label | df.loc[df["ada"] == 1, "station"] |
| By position | df.iloc[:5, :3] |
| A new column | df["hours"] = ... (a whole column at once, like NumPy) |
| Text and date parts | df["lines"].str.count("/"), df["start"].dt.hour |
Half the outages are over in under 2 hours, a quarter last more than 4, and two planned jobs took a month. The MTA's estimate is longer than the real outage 98% of the time: it plans for the worst.
Which line keeps elevator outages at ADA-accessible stations that lasted over 4 hours?
- f[f["kind"] == "EL" and f["ada"] == 1 and f["hours"] > 4]
- f[f["kind"] == "EL" & f["ada"] == 1 & f["hours"] > 4]
- f[(f["kind"] == "EL") & (f["ada"] == 1) & (f["hours"] > 4)]
& combines them row by row. Brackets are needed because & is evaluated before ==.Columns are whole arrays: filter with a True/False column, combine conditions with & and |, and build new columns in one line.
3. Group, then combine
groupby is three steps under one name: split the rows by a key, apply a summary to each group, combine the answers into a table. Step through it on six outages:
1. the rows
2. split by reason
3. apply, combine
Why pass validate="many_to_one" to merge?
- It raises an error if a station appears twice in the right table, which would silently duplicate outage rows
- It makes the merge faster
- It drops outages whose station isn't found
groupby is split, apply, combine; merge pairs every row with every match, so say what shape of match you expect.
Where it breaks: three silent pandas bugs
- A merge that multiplies rows. Merge 3 outages at a station with a table that lists that station 4 times (say, once per entrance) and you get 12 rows. Every sum and count after it is inflated, and nothing complains. Check
len()before and after, or passvalidate=. - Changing a copy of a slice.
f[f["ada"] == 1]["hours"] = 0changes a temporary table and then throws it away, sofis unchanged; pandas prints a warning, but the line runs and the warning is easy to miss. Writef.loc[f["ada"] == 1, "hours"] = 0: one step, intof. - Averages of tiny groups. One station with a single 700-hour outage tops a "worst stations by mean hours" list. Always show the count next to a group's mean, and sort by something that needs enough data (or the median).
4. scikit-learn's one contract
Every piece of scikit-learn follows the same few rules, which is why any model drops into any pipeline:
| Method | What it does | Who has it |
|---|---|---|
fit(X, y) | Learns from training data and stores what it learned (attributes ending in _, like coef_ or mean_) | everything |
transform(X) | Applies what was learned to new rows | scalers, encoders, imputers |
predict(X), predict_proba(X) | Answers for new rows | models |
get_params(), set_params() | The settings you chose (hyperparameters), separate from what it learned | everything |
A pipeline chains them, and is itself one estimator: fit fits every step on the training rows in order, predict runs new rows through all of them. The question here: will an outage last more than 4 hours (27% of them do)? An app could warn riders to plan another route.
Logistic regression edges out the trees here (about 0.89 against 0.88, and steadier from fold to fold): with 600 rows and a few strong categories, the simpler model has less to overfit. That's chapter 13's table in practice: start simple, and let the validation numbers decide.
Every scikit-learn piece learns in fit and applies in transform or predict, so a pipeline of them is one model you can swap, score and tune.
Why fit and transform are separate methods
- A scaler needs two numbers per column, a mean and a spread, and they have to come from somewhere.
fitis where it learns them, from the rows it's given, and stores them (mean_,scale_).transformonly applies the stored numbers. It never looks at the new rows' own mean.- So "learn from training rows, apply to everything" isn't a rule you have to remember: it's built into which method does what. Cross-validation calls
fiton each fold's training rows andtransformon its test rows, and no test row can shape the scaling. fit_transformis just both on the same rows: right for training data, a leak if you call it on test data.
5. Tuning: grid search with the right split
Hyperparameters are the settings you choose before fitting: the penalty strength C, the depth of trees, the learning rate. GridSearchCV tries each combination with cross-validation and keeps the best. In a pipeline, a step's setting is named step__setting (two underscores).
Search on a log scale (0.01, 0.1, 1, 10): the effect of a penalty depends on its order of magnitude, not on its exact value. When the grid gets big, RandomizedSearchCV tries a fixed number of random combinations instead, and usually finds as good a setting in far fewer tries.
Grid search reports a best CV AUC of about 0.9. What is that number?
- An honest estimate of the AUC on future outages
- The best of five settings by validation score, so a little optimistic: confirm on held-out later data
- The training AUC
Hyperparameters are chosen by cross-validation over a log-scale grid, and the winner's score is optimistic until it's checked on data nobody chose with.
6. What to carry forward
- Look first:
info(),describe(),value_counts(), the min and max dates. Real tables have stories. - Filter with True/False columns and
&, add columns whole, use.strand.dt, write with.loc. - groupby = split, apply, combine; show counts next to means. merge with
validate=and check the row count. - scikit-learn: fit learns, transform/predict apply; a pipeline is one estimator; time-ordered data gets
TimeSeriesSplit. - Tune on a log scale with
GridSearchCVorRandomizedSearchCV; the best CV score is optimistic.
All lessons: AI from scratch. Kaggle Learn's free Pandas and Intermediate ML courses are good companions.
Last updated