Semester 1 · Week 05
The Python stack and cleaning data
- Ch 6 Python Data Science Ecosystem
- Ch 7 Data Cleaning & Wrangling
Chapter 6: The Python data science ecosystem
Know which layer a problem lives in.
Notes · slide 2
Time: 50 minutes for two chapters. About 20 on Chapter 6, 25 on Chapter 7, and 5 to check understanding.
Say: Python wasn't designed for data science. It won because of a stack of libraries, each fixing what the layer below can't. Tonight is a map of that stack, then the work that takes most of a data scientist's time: cleaning.
Key line: know which layer a problem lives in.
Next: why the layers matter.
Why the layers matter
- Every later chapter assumes this stack.
- The goal isn't memorised syntax. It's knowing which library to reach for, and why.
- A slow loop over a NumPy array is suspect on sight.
- A sklearn shape warning traces straight to array shape.
Notes · slide 3
Say: Every later chapter assumes this stack. Not memorised syntax: Appendix A has that. What matters is knowing which library to reach for and why.
Say: Knowing the layers turns hours of searching into minutes. A slow loop over a NumPy array is suspect on sight. A shape warning from sklearn traces to array shape. A seaborn chart you can't adjust gets fixed one layer down in matplotlib.
Ask: "Who has hit a pandas error they didn't understand?" Collect one or two. You'll likely place them on the next slide.
Next: the stack.
The layered stack
| Layer | Library | Role |
|---|---|---|
| ML algorithms | scikit-learn, XGBoost, statsmodels | Models, preprocessing, metrics |
| Tables | pandas | Labelled tabular data |
| Charts | matplotlib, seaborn | Drawing and exploring |
| Science | scipy | Tests, optimisation |
| Arrays | NumPy | Fast numerical arrays |
Each layer builds on the one below.
Notes · slide 4
Say: Read it from the bottom. NumPy gives fast arrays. scipy adds tests and optimisation. matplotlib and seaborn draw. pandas adds labels and mixed types. scikit-learn, XGBoost, and statsmodels put models on top.
Say: The layers leak in useful ways. pandas columns are NumPy arrays underneath. That's why pandas is fast, why .to_numpy() exists, and why sklearn wants arrays in the end.
Key line: you don't need C to use NumPy. You do need NumPy to use pandas well.
Next: the bottom layer.
NumPy: fast arrays
- Python loops check types and allocate objects on every step.
- NumPy stores one type in one contiguous block, and loops in C.
- Broadcasting applies an operation across compatible shapes with no explicit loop.
import numpy as np
x = np.arange(1_000_000)
y = x * 2 # one call, no Python loopNotes · slide 5
Say: A Python loop checks the type, looks up the operator, and creates a new object on every step. At a million elements, that overhead dominates. NumPy stores one type in one block of memory and runs the loop in C. Typically 50 to 200 times faster for simple operations.
Say: Broadcasting stretches shapes to match without a loop: array + 5 adds 5 everywhere. Careful: shapes that line up by accident broadcast silently and give a wrong answer.
Ask: "What does [1, 2] + [3, 4] give with lists? With arrays?" Listen for: joined lists, then element-wise sums.
Next: labels on top.
pandas: labelled tables
- A Series is one labelled column. A DataFrame is a labelled table, with a type per column.
- The index labels every row. pandas aligns data on it automatically.
- Built on NumPy, so column operations stay vectorised.
Notes · slide 6
Say: NumPy has no column names, no row labels, and one type per array. Real data has all three. pandas adds a Series, one labelled column, and a DataFrame, a table with a type per column.
Say: The index labels every row, not just its position. pandas lines up data on it automatically. That helps with joins and time series, and surprises people when two indexes don't match.
Key line: columns are NumPy arrays underneath, so keep operations on whole columns, not row loops.
Next: charts.
Charts: matplotlib and seaborn
- matplotlib draws. Precise control, every element spelled out.
- seaborn explores. DataFrame-aware, good defaults, statistical chart types.
- Start EDA in seaborn. Drop to matplotlib when you need a detail seaborn doesn't expose.
Notes · slide 7
Say: matplotlib is for drawing. Every element is spelled out, so you can control anything. seaborn is for exploring. It understands DataFrames, has good defaults, and has the statistical charts you'll want: distributions, pair plots, heatmaps.
Say: seaborn returns a matplotlib figure. So any seaborn chart can be adjusted with matplotlib.
Key line: start exploration in seaborn. Drop to matplotlib for the detail.
Next: the model layer.
scikit-learn: one API for everything
| Method | Does |
|---|---|
.fit(X, y) |
Learn from data |
.predict(X) |
Predict |
.transform(X) |
Transform, for preprocessing |
.score(X, y) |
Evaluate |
Learn LogisticRegression and you already know RandomForestClassifier.
Notes · slide 8
Say: Every estimator follows the same pattern. Fit learns. Predict predicts. Transform transforms. Score evaluates. Learn one model and you know how to call them all. The effort goes into understanding the algorithm, not the interface.
Say: A preprocessing step learns its settings, like a scaler's mean, on training data only. Fit on train, transform test with the same fitted object. Fitting on the test set leaks, and nothing warns you.
Ask: "Why might a scaler fitted on the whole dataset make results look better than they are?" Listen for: test statistics leak into training.
Next: the worked example.
Worked example: the speed gap
Double one million numbers.
| Method | Time |
|---|---|
| Python list comprehension | 27.7 ms |
| NumPy | 0.24 ms |
117 times faster, and the gap grows with size.
Notes · slide 9
Say: Double one million numbers. A list comprehension takes about 27.7 ms. NumPy takes 0.24 ms: 117 times faster, inside the 50 to 200 range. The gap grows with size.
Key line: a Python loop over numbers is a smell. Look for the vectorised version first.
Say: Timings vary by machine. The ratio is the point, not the milliseconds.
Next: a real question in one line.
Worked example: Titanic in one line
Survival rate by class and sex:
| Class | Women | Men |
|---|---|---|
| First | 97% | 37% |
| Third | 50% | 14% |
Survivors paid £48.40 on average, non-survivors £22.12. A t-test gives p≈6×10−15.
Notes · slide 10
Say: One grouped aggregation answers whether survival depended on class and sex. First-class women 97%, first-class men 37%. Third class: 50% and 14%. Both mattered, and together. Group by one at a time and you'd miss that.
Say: Survivors paid £48.40 on average, against £22.12. The t-test p-value is about 6 × 10⁻¹⁵. But fare tracks class, and class tracks survival.
Key line: a significant p-value says a difference is unlikely to be chance. It doesn't say what causes it.
Next: the chapter in one idea.
Mental model
- NumPy is the raw material.
- pandas is the workbench.
- matplotlib and seaborn are the drafting table.
- scikit-learn is the instrument kit.
You'll use pandas and scikit-learn in nearly every project.
Notes · slide 11
Say: NumPy is the raw material. pandas is the workbench. matplotlib and seaborn are the drafting table. scikit-learn is the instrument kit.
Say: One habit from the notebooks: restart the kernel and run all cells top to bottom before you trust a result. Running cells out of order leaves hidden state.
Next: Chapter 7, cleaning data.
Chapter 7: Data cleaning and wrangling
A model faithfully learns whatever corruption you give it.
Notes · slide 12
Time: about 25 minutes for this chapter.
Say: Real data arrives with gaps, typos, duplicates, wrong types, and encoding errors. A model doesn't average the mess away. It learns it.
Key line: cleaning isn't the chore before the real work. On most projects it is the real work.
Next: why it takes so long.
Why cleaning takes so long
- Surveys put cleaning at 40–80% of a data scientist's time.
- A model survives a poor hyperparameter. It doesn't survive corrupted labels.
- The fix is a repeatable loop: find, understand, decide, validate.
It's Boyd's OODA loop applied to data. Never treat a value before you understand why it's there.
Notes · slide 13
Say: Surveys put cleaning at 40 to 80% of a data scientist's time. Not inefficiency. The risk is uneven. A model survives a slightly wrong hyperparameter. It doesn't survive corrupted labels.
Say: Use a loop: find the problem, understand why it's there, decide on a treatment, validate it worked. It's John Boyd's OODA loop from fighter pilots: observe, orient, decide, act.
Key line: never treat a value before you understand why it's there.
Next: missing values.
Missing values: the mechanism matters
| Mechanism | Missingness depends on | Risk |
|---|---|---|
| MCAR | Nothing | Safe to drop or impute |
| MAR | Other observed columns | Impute using those columns |
| MNAR | The missing value itself | Naive imputation is biased |
High earners skipping the income question is MNAR. Filling with the mean underestimates income.
Notes · slide 14
Say: Why a value is missing decides what you can safely do. MCAR: missing at random, like a sensor dropping a reading. Safe to drop or fill. MAR: depends on other columns you have. Fill using those columns. MNAR: depends on the missing value itself.
Say: High earners skip the income question. Fill with the mean and you underestimate income, because the gaps are the high values.
Ask: "Patients drop out of a study because they feel better. Which mechanism?" Listen for: MNAR. The missingness depends on the outcome.
Next: what to do about it.
Treatments for missing data
| Strategy | When |
|---|---|
| Drop rows | Under ~5% missing, MCAR |
| Median fill | Numeric and skewed |
| Mode fill | Categorical |
| Forward fill | Time series, short gaps |
| KNN or model-based | Other columns predict the missing one |
Fit imputers on training data only, or you leak.
Notes · slide 15
Say: A ladder. Drop rows: fine under about 5% missing, if MCAR. Fill with the median for skewed numbers, the mode for categories. Forward fill for short gaps in time series. KNN or a model when other columns predict the missing one. Higher rungs keep more information and take more work.
Say: Two rules. Fit any imputer on training data only. And never impute the label. That trains the model on guesses of itself.
Ask: "Why median rather than mean for income?" Listen for: skew. A few huge values pull the mean.
Next: outliers.
Outliers: informative or harmful?
IQR fence: [Q1−1.5IQR, Q3+1.5IQR]z-score: ∣z∣>3
- A CEO's salary is a real outlier. Removing it discards signal.
- An age of 312 is an error.
- Options: remove, cap (winsorise), transform, or flag and keep.
Notes · slide 16
Say: Two common detectors. The IQR fence uses quartiles, so it's robust to skew. The z-score flags values more than three standard deviations out. It assumes a bell shape, and a big outlier inflates the standard deviation and can hide itself.
Say: Far isn't wrong. A CEO's salary is real. An age of 312 is an error. Remove errors. Cap real values that shouldn't dominate. Log-transform a long tail. Or flag and keep: in fraud, the outlier is often the signal.
Key line: the question is always whether it's informative or harmful.
Next: the problems that don't announce themselves.
The quiet problems
- Duplicates: copies in both train and test inflate accuracy.
- Wrong types: one
'unknown'makes a number column text.'10' > '9'isFalse. - Encoding errors:
São Pauloread with the wrong encoding becomesSão Paulo. - Inconsistent categories:
'F','female'and'FEMALE'are three categories to a model. - Schema violations: a negative age,
'not a date'in a date column.
Notes · slide 17
Say: Duplicates split across train and test inflate accuracy. The model is tested on rows it has memorised. Wrong types: one "unknown" turns a number column into text, and text compares letter by letter, so "10" is less than "9". Encoding errors: São Paulo read with the wrong encoding becomes São Paulo, and one city becomes two categories. Inconsistent categories: F, female, and FEMALE are three values to a model. Schema violations: a negative age parses fine and still means nothing.
Key line: none of these crash. That's what makes them dangerous.
Next: the worked example.
Worked example: a planted mess
505 synthetic employee rows, with known defects:
- 5 exact duplicates
agemissing in 39 rows, with one age of 312- 10 spellings of two gender values
years_exploaded as text- 2 invalid dates
- 8 city names hit by an encoding error
Notes · slide 18
Say: The notebook builds a mess on purpose, so we know every defect in advance. 500 employees, plus 5 duplicates. Missing ages, one age of 312, ten spellings of two genders, experience stored as text, two invalid dates, and eight corrupted city names.
Ask: "Before cleaning, which of these would you check first, and why?" Listen for: duplicates first, then types. Everything after depends on them.
Next: cleaning it in order.
Worked example: cleaning in order
Duplicates → types → categories → encoding → outliers → missing values → validation.
- Deduplication: 505 → 500 rows.
- Encoding repair: all 7 visibly mangled cities restored.
- IQR flags only the 312. A domain cap of 16–90 states what a valid age is.
- Result: 498 clean rows and no silent errors.
Notes · slide 19
Say: Order matters. Duplicates first, so later counts are right. Then types, categories, encoding, outliers, missing values, and validation. 505 rows become 500. Encoding repair restores all seven visibly mangled cities. The IQR fence flags only the 312. A domain cap of 16 to 90 then states what a valid age is.
Say: The eighth encoding error hit a plain-ASCII name, so nothing looked wrong. Only understanding the cause finds it.
Key line: 498 clean rows, under 1.5% lost, and every change made on purpose.
Next: the loop.
Cleaning is a loop

Find, understand, decide, validate. Then go round again: each fix can expose the next problem.
Notes · slide 20
Say: Find, understand, decide, validate, then go round again. Each fix can expose the next problem. Removing duplicates changes the counts. Fixing types reveals new outliers.
Say: Validation is the step you never skip. Compare each column before and after. Cleaning that flattens real variation looks tidier and is worse.
Lab: write a clean() function, not a notebook of one-off edits. That function is one pass round this loop, written down.
Next: the chapter in one idea.
Mental model
Data cleaning is defensive programming for a dataset.
- Every unchecked assumption is a bug waiting to surface in predictions.
- The goal isn't a perfect dataset.
- It's one where every anomaly was noticed, understood, and handled on purpose.
Notes · slide 21
Say: Data cleaning is defensive programming for a dataset. Every unchecked assumption is a bug waiting to show up in predictions.
Key line: the goal isn't a perfect dataset. It's one where every anomaly was noticed, understood, and handled on purpose.
Next: check yourself.
Check yourself
- A sensor drops readings when it overheats, which happens on hot days. Which mechanism is that?
- Why remove duplicates before splitting train and test?
- When would you cap an outlier rather than remove it?
- Your number column has dtype
object. What's the likely cause?
Notes · slide 22
Do: pairs, three minutes, then take answers.
Answers: 1. MNAR if the missing value is the high temperature itself. MAR if a recorded temperature column predicts it. 2. Duplicates across the split inflate test scores. 3. When the value is real but extreme. 4. One non-numeric entry in the column.
Lab: the Air Quality dates are month first. Learners who parse them day first get a calendar with holes. Let them find it, then ask what check would have caught it.
This week
- Read Chapter 6: Python Data Science Ecosystem.
- Read Chapter 7: Data Cleaning & Wrangling.
- Take the Chapter 6 quiz.
- Take the Chapter 7 quiz.
- Run the notebooks: Chapter 6 (opens in a new tab),Chapter 7 (opens in a new tab).
- Optional: the further reading for week 5.
Slide 1 of 23: The Python stack and cleaning data
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.