Cleaning, missing data and outliers: deciding what the collected data can support.
Knowledge Discovery in Data · University of the Philippines Cebu
Locate the gaps, determine their cause, then drop or fill deliberately.
Flag extreme points with the IQR rule, then judge each one before deleting anything.
Every cleaning step changes the results, so each is done in code and recorded.
Weeks 3–4 covered acquiring data. CRISP-DM (week 2’s six-step project cycle) calls the next stage Data Preparation; it is where projects spend most of their time.
Cleaning is more than correcting typos. It is a series of judgments that a reader must be able to audit.
Whatever the source (parsed HTML or an API's JSON), the rows arrive with gaps, duplicates and implausible values. Raw data is unverified until it has been checked.
Nothing guarantees that the values are complete, consistent or even possible.
Every later analysis inherits the data's flaws: flawed input yields flawed output, however confident it looks.
Values that are absent and values that are implausible.
Programmers mark missing values with numbers such as −99999999.
A floating-point standard adds NaN, “not a number”.
William Kahan, its main architect, receives computing’s highest prize.
Marks a missing number with numpy.nan.
A code such as −99999999 is dangerous because it is a real number: an average includes it silently.
NaN is a special value that means “no valid number here”. It is what 0/0 produces in floating-point arithmetic.
SourceWikipedia: NaN; William Kahan; pandas: Working with missing data
np.nan == np.nan is False, so missing values are found with isna(), never with ==.
np.sum([1, np.nan]) is nan: one missing value spoils a NumPy total.
pd.Series([1, np.nan]).sum() is 1.0: pandas leaves NaN out by default.
The last two disagree, so the same column can give different totals in NumPy and pandas.
3.14; NaN is one of its special valuesSourceWikipedia: NaN; outputs from NumPy 2 and pandas 3 on the lecture laptop
"Most of a working data scientist’s time goes to the topics of this week and next: finding gaps, investigating unusual values, and justifying the decisions made about both."The reason CRISP-DM draws Data Preparation as the largest loop
A frequently cited figure is "80% of the work." The exact share varies, but preparation consistently takes more time than modeling.
Data preparation is not a preliminary to the analysis; it is a central part of it.
A cell where nothing was recorded. It can mean “unknown”, “not yet” or “refused”.
e.g. an unfinished project has no completion date
“Not a Number”: how pandas marks an empty cell. Summaries skip it; .isna() finds it.
e.g. df.isna().sum() counts NaNs per column
The general word for “no value”: JSON’s null, Python’s None. pandas treats both as missing.
e.g. week 4’s "closed_on": null
Filling a gap with a chosen stand-in value instead of dropping the row.
e.g. fillna(df.temp.mean())
Three “typical values”: the average; the middle value once sorted; the most common value.
e.g. for 8, 12, 12, 45, 80: 31.4 / 12 / 12
A row identical to an earlier one. It is counted twice in every total.
e.g. the same project scraped twice
What kind of values a column holds: whole numbers, decimals, text, dates. pandas calls it dtype.
e.g. int64, float64, object (text)
A value far from the others. Far is not the same as wrong: it may be a typo or a genuine finding.
e.g. 98 in a row of 12s
The three cut points that split sorted data into four equal groups: Q1, the median, Q3.
e.g. Q1 = 12 and Q3 = 14 for the example series
Interquartile range, Q3 − Q1: the width of the middle half. Fences sit 1.5 IQRs beyond it.
e.g. IQR = 2, fences at 9 and 17
The typical distance of values from their mean. A large SD indicates widely spread values.
e.g. s.std()
How many standard deviations a value sits from the mean. Beyond 2 or 3 is the usual flag.
e.g. the 98 has z = 2.66
Rescaling a column to z-scores (mean 0, SD 1) or into the range 0 to 1.
e.g. week 6 uses both before comparing columns
Absent values and the meaning of their absence.
Loading a table into pandas and inspecting its columns is already familiar. This part adds the first question to ask of any new table: which cells are empty, why, and how to treat them.
A sensor failed, a survey question was skipped, or a form field was optional.
Joins that did not match, or scrapes where a tag was absent (.get() returning None in earlier weeks).
People decline questions on income, health or politics for reasons. The gap carries information.
A missing value is a cell where nothing was recorded. In pandas,
all of these appear identically as NaN. The cell does not record the cause; it must be inferred.
null, Python None); pandas treats these as missing tooA random glitch and a deliberate refusal require different treatment: the same NaN, but a different decision.
isna().sum() is the first check on any new dataset. Per-column counts show where the gaps are; a single total hides this.
A column that is 2% empty and one that is 60% empty are different problems: the first may be filled, the second may be dropped entirely.
pd.DataFrame({…})a tiny weather table: five cities, three columns; np.nan is an empty celldf.isna()a same-shaped table of True (empty) / False (filled).sum()adds each column’s Trues (True counts as 1): the gaps per columntemp 2two cities (Davao, Tacloban) have no temperature; city is complete.any(axis=1)True for a row with at least one gap; axis=1 means “look across each row”Last week these records were retrieved through an API to total their budgets. The same API serves the whole table in one call, so this week begins where it left off, with the question that should always come first: which values are missing, and for what reason.
Real DPWH flood control projects, 2016–2026, in the public domain. Every number on the following slides is computed from exactly this response.
requests.get(url)ask the API for the whole table at once. Week 4 used /api/flood/projects, which returns one page at a time; export.csv is the bulk doorio.StringIO(r.text)hand the downloaded text to pandas as if it were a filedf.shape → (34079, 15)34,079 rows (projects) and 15 columnsThe same one-line check as for the small example, now applied to records of public spending.
The other ten are complete. This is useful to know before any cleaning is planned.
.sort_values(ascending=False)sort the counts in descending order, so the columns with the most gaps appear first64146,414 of 34,079 projects have no completion date: 18.8%Exactly 9.38% of rows.
Exactly the same count.
The same rows in both columns, which indicates a common cause.
A matched pair like this is a structural gap (caused by how the data was built): the geocoding step (turning an address into map coordinates) either ran for a row or it did not. Filling latitude without longitude would invent a location in the sea.
df[['latitude','longitude']].isna().sum(axis=1).value_counts() — gaps per row (axis=1), then how many rows have each count. The expected counts are only 0 and 2, never 1. The result: 30,884 rows with 0 and 3,195 with 2.
Whether a gap is random can be tested rather than assumed. A cross-tab places the missingness next to another column: one column’s pattern broken down by another’s groups.
If the gap were random, every status would show a similar percentage. The output shows otherwise.
df.groupby("status")split the rows into piles, one per status["completion_date"]in each pile, look only at the completion date column.apply(lambda s: s.isna().mean())run a tiny nameless function (lambda) on each pile: the share of empty cells (mean of True/False = fraction True)0.0 / 1.00% missing or 100% missing: nothing in between0% missing. A finished project has a finish date.
100% missing. It has not finished, so there is no date to record.
100% missing. The contract has not yet been awarded.
Every status is either 0% or 100% missing. This is the opposite of "missing at random" (gaps that fall anywhere, like coin tosses): the empty cell carries the information.
"completion_date is missing exactly when the project is unfinished." Once the cause is stated, the appropriate treatment follows, and it is not a fill.
The 876 For Procurement rows are missing three fields at once, and they are the same 876 rows each time.
No contractor has been chosen, no amount agreed, and no completion date is possible. The row is accurate; it records an early stage.
df[df.status == "For Procurement"]a boolean (True/False) filter: test every row, keep only the rows where the status matchesfp.contractor.isna().sum()how many of those rows have no contractor(fp.budget == 0).sum()how many have a budget of exactly 0 (True counts as 1)The treatment depends on why the value is missing. There are three broad cases, ordered from least to most harmful.
A missing exam score can mean the paper got lost (random), the student was sick during flu season (explained by a known variable), or the student skipped an exam they expected to fail (the gap itself carries information).
The gap is unrelated to any variable, as with a dropped network packet. Dropping or filling is safest here.
Older stations miss more readings. The gap is predictable, so a group-aware fill can work.
High earners skip the income question. Dropping them silently biases every later result, so any treatment must be stated.
dropna() invents nothing; it discards rows. The cost is every other value in those rows, which is lost with the gap.
When few rows are affected and the gaps appear random. It is not acceptable when 40% of a column is lost or the missing rows share a pattern.
np.nanNumPy’s missing-value marker (from import numpy as np)df.dropna()a new table with every row that has a gap removed; df itself is unchanged0, 2, 3the row labels keep their old numbers, which shows that rows 1 and 4 were droppedFilling a gap with a stand-in value is called imputation.
fillna() replaces each gap with a stand-in, often the column mean or median. No rows are lost, but some values are invented.
df["temp"].mean()the average of the values that exist: (31 + 33 + 29) / 3 = 31.0df.fillna(…)put that number into every empty cellMean-filling pulls values toward the average and reduces the spread. The more values are filled, the less the column reflects the real data.
Three different “typical values” can be used for filling. They agree on well-behaved data and differ markedly when one value is extreme, such as the 80 mm day here.
In a sari-sari store, the mode is the best-selling item, the median is the customer in the middle of the queue, and the mean is each share of a bill split equally.
pd.Series([…])one column of values; np.nan is the gaprain.mean() → 31.4pulled up by the 80: higher than four of the five readingsrain.mode()[0]mode() returns a list-like Series (there can be ties); [0] takes the firstThe global mean on the previous slide filled both gaps with 31.0. A group mean fills the Luzon gap with the Luzon average (29.0) and the Visayas gap with the Visayas average (32.0), closer estimates for each.
A missing Luzon reading is estimated from other Luzon readings, not from the Visayas. The group is the set of similar rows the estimate borrows from.
transform("mean") builds a column holding each row's group average; fillna then uses it only where values are missing.
The lab asks for this code and an explanation of why it improves on the global mean.
It runs instantly and returns a complete frame, but the result is misleading.
Dropping every row with any gap produces a tidy table. The row counts show the cost.
A quarter of the public record is removed without any recorded decision.
clean = df.dropna()a new table without any row that had a gap; df keeps all rowslen(df), len(clean)two row counts side by side: before and afterdropna() did not remove a random quarter. It removed every unfinished project in the country, because an unfinished project is exactly the case that leaves a blank.
(value_counts() counts how many rows have each value.)
Each row is one status. The gaps are not random: an unfinished project has no completion date yet, so a whole-frame dropna() removes every one of them along with its other, complete values.
Every statistic computed on the dropped table describes finished projects only. The completion rate, for example, rises from 80.8% to 99.6%.
No single row in clean is false; every row is real. However, the set of rows now describes a country where flood control projects almost never stall.
Survivorship bias: drawing conclusions only from the cases that made it through a filter. In WWII, analysts studied bullet holes on the planes that came back; the planes hit elsewhere never returned to be counted.
df.dropna()It treats every column’s gaps as the same problem, although they differ.
df.dropna(subset=["budget"]) — "rows with no budget cannot answer a budget question."
df["is_finished"] = df.completion_date.notna() adds a flag and keeps every row.
Test: the drop should be defensible in one sentence to a reader who disagrees with the conclusion. Otherwise the step shapes the result rather than cleaning the data. (subset= checks only the named columns; notna() is the opposite of isna().)
Read the CSV. Run isna().sum(). Identify the column with the most gaps.
Take start_date (973 missing). Cross-tab it against status and against year.
Decide whether the gap is random or informative. Write a one-sentence footnote that justifies the decision.
Compare the sentence with a neighbour’s. A disagreement indicates that one of the two has found something.
Required code: df.groupby("status")["start_date"].apply(lambda s: s.isna().mean()), the same method as on the cross-tab slide.
Running df.dropna() on the flood data removes 8,709 rows. What has happened to the analysis?
A survey's income column is 35% empty, and high earners are suspected of skipping it. Should it be filled with the column mean?
B: the gap is informative.
If the missing values were mostly high, filling them with the average of the answered ones writes systematically low numbers into exactly the rows that were highest. Any treatment here must be declared, not hidden inside a one-liner.
The treatment depends on the cause, which is why Part A began with sources of missing values.
Count, diagnose, then treat, in that order.
A duplicate is a row identical to an earlier one. Scrapes that fetch a page twice, or files combined twice, create them without warning, and every later count and sum is inflated.
A class list with one student entered twice gives a wrong headcount, average grade and pass rate.
There are no repeated rows and no repeated contract ids. The check takes one line and prevents double-counting.
t.duplicated()True for each row that repeats an earlier row; the first copy stays False.drop_duplicates()a new table with the repeats removed: 3 rows in, 2 outdf.contract_id.duplicated()repeats in one column only: a contract id should never appear twiceA column’s data type (pandas says dtype) determines the operations it supports: adding numbers, sorting dates, searching text. When a CSV is loaded, pandas infers each type from the values.
start_date
looks like 2022-07-14 but is stored as text: two dates cannot be subtracted until the column is converted.
df[[…]]keep four columns (a list of names inside the brackets).dtypesthe data type of each columnpd.to_numeric converts text such as "31" into the number 31.
A single non-numeric cell stops it with an error. A traceback (the error report) is read from the bottom up:
ValueErrorlast line first: the type of error. A ValueError means the right kind of input with an unusable value"n/a" at position 1the message: which value, and where (counting from 0: the second cell)line 3the script line that triggered it: the to_numeric callerrors="coerce" turns
anything unreadable into NaN instead of stopping: the bad cell becomes a missing value that can be counted, as in Part A.
Next: values that are present but implausible.
Values far from the rest, which are not necessarily wrong.
Part A dealt with values that are absent. This part deals with values that are present but surprising: how to flag them with a rule, then how to judge them.
An outlier is a value far from the others. The definition concerns distance, not truth. The 98 in a row of 12s may be a typo or a genuine finding.
(pd.Series makes one column of values.)
A data-entry error (9.8 typed as 98) or a real reading from an extreme day. The same number has opposite meanings.
Flagging is mechanical (this part); judging requires inspection (the next part).
Sort the values. The quartiles cut them into four equal groups: Q1 is a quarter of the way up, Q3 three quarters. The middle 50% runs from Q1 to Q3, and its width is the IQR (interquartile range). Any value more than 1.5 × IQR outside that box is flagged. The same rule defines the whiskers of a boxplot.
When a class lines up by height, the middle half is the box, a fence sits one and a half box-widths beyond each end, and anyone past a fence is examined more closely.
s.quantile(0.25), s.quantile(0.75)Q1 = 12.0 and Q3 = 14.0 for this seriesiqr = q3 - q114 − 12 = 2: the width of the middle halflow, highfences at 12 − 3 = 9.0 and 14 + 3 = 17.0(s < low) | (s > high)below the low fence or (|) above the high one6 98row label 6 holds the value 98: the only point past a fenceQuartiles barely change when an extreme value appears, so the fence is not distorted by the point it is meant to detect.
"The 1.5×IQR fence comes from John Tukey, who reportedly chose it because 1 was too strict and 2 too lenient. It is used because it is useful, not because it is fixed."The rule identifies candidates for inspection, not errors
Skewed data, small samples and heavy-tailed measurements (where extreme values are common) all weaken the rule. It is a starting point, not a verdict.
Z-scores (distance in standard deviations) are simpler, but the mean and SD they rely on are themselves affected by outliers.
The standard deviation (SD) is the typical distance of values from their mean. A z-score says how many SDs a value sits from the mean; a value beyond 2 (or 3 on large data) is usually flagged. Turning every value into its z-score is called standardising; squeezing values into 0 to 1 is normalising (week 6).
The 98 is inside the mean and SD it is measured against. Without it the SD is 1.31; with it, 28.36. The outlier inflates the scale it is measured on, so several large outliers can mask each other.
s - s.mean()each value’s distance from the mean (22.44)/ s.std()measured in standard deviations (28.36) instead of in millimetresz.abs() > 2abs drops the minus sign; keep values more than 2 SDs away, either side2.66the 98 is 2.66 SDs above the mean; every other value is within half an SDImpossible values: a 250°C afternoon in Cebu, a negative age, a unit slip (meters logged as millimeters). Correct it from the source where possible; otherwise treat it as missing.
Rare but real: the rainfall the day a typhoon hit, one viral post among thousands, a billionaire in an income survey. Deleting these removes the most important observations.
The deciding question is not whether the value is far out, but whether it could actually occur and whether the analysis must include such cases.
Run the analysis both ways and report both (a sensitivity check, which shows whether the answer changes). This is preferable to unwarranted certainty.
The value is real and the question includes extreme days. Robust summaries (ones barely moved by extremes, like the median) prevent one point from dominating.
Capping (statisticians say winsorizing): s.clip(upper=high) pulls extremes in to the fence. The row is kept, but its leverage is reduced.
For values that cannot be true and cannot be corrected. The number removed and the reason are recorded; an undocumented deletion is a hidden change to the data.
In the lab, capping the single 98 leaves eight values unchanged, yet the mean drops from 22.4 to 13.4.
One point determined most of the average. This is leverage (one value’s power to move a result), the subject of the next slide.
Every value affects the mean, so one very large value moves it substantially. The median depends only on order, which one extreme point barely changes.
If ten jeepney passengers each earn ₱20,000 a month and a billionaire boards, the mean income rises into the millions while the median is unchanged.
When outliers are suspected, report the median and use it for filling. A large gap between mean and median is itself a finding.
The shape of the distribution comes before any flagging. A long right tail (most values small, a few very large ones stretching the range to the right: the data is skewed) is normal for money, and it makes the mean a poor summary.
Half of all projects lie under ₱37.7M. The largest is ₱1.45B. Both facts are true and neither is an error.
pd.set_option(…)display setting: show numbers with commas and no decimals.describe()an eight-number summary: count, mean, SD, smallest, quartiles, largest25% / 50% / 75%Q1, the median, Q3The formula is the same as in the small example; the result is now a peso amount of public interest.
2.34% of the dataset sits above the upper fence. These rows are for inspection, not deletion.
quantile([.25, .75])both quartiles at once: about ₱14.6M and ₱67.5MfenceQ3 + 1.5 × IQR: about ₱146.9M(df.budget > fence).sum()how many budgets are above it: 798| Budget | Region | Description |
|---|---|---|
| ₱1,447,499,996 | Central Office | Construction of small river impounding project |
| ₱1,096,255,230 | Central Office | Construction of bank protection works |
| ₱1,042,782,802 | Central Office | Construction of bank protection works |
All three are Central Office (DPWH’s national headquarters) entries — national-scale works, not regional ones. The fence identified rows worth inspecting, and inspection showed that they are valid.
Deleting them would remove the country’s largest flood control projects from an analysis of flood control spending.
The mean is pulled upward by the same 798 projects the fence flagged. The median does not move.
"Typical project" refers to the median. Many readers also interpret "average" as the median, so the median is the clearer figure to report.
round(df.budget.mean())the average budget, rounded to whole pesos: about ₱47.0Mround(df.budget.median())the middle budget: about ₱37.7M1.25the mean is 1.25 times the median, i.e. 25% higherThese values are not large but impossible. The 0 is a placeholder: a value typed in to fill a slot, not a measurement. A zero-peso construction contract indicates a project without a contract, not a low-cost one.
876 are For Procurement. The remaining 63 are Terminated. Both are "no money moved", recorded as 0 rather than as blank.
The mean budget drops, because contracts that do not exist are averaged in.
df.budget.replace(0, np.nan): the mean then describes real contracts only.
df[df.status.isin(["Completed","On-Going"])] — isin keeps rows whose status is in the list; the population must be stated.
As with week 4’s amount_paid, a column of zeros is a claim that must be checked: it may mean zero or unknown.
Compute the IQR fence within each region instead of across the whole country. Does Region III flag different projects?
Open the descriptions of any three flagged rows. Do they look like errors or like large projects?
Choose keep, cap or remove, and write the reason next to each.
df.groupby("region").budget.transform(lambda s: s.quantile(.75) + 1.5*(s.quantile(.75)-s.quantile(.25)))
939 flood projects
have budget == 0. Should they be included when computing the average project budget?
Daily rainfall for Tacloban, November 2013. One day reads 600 mm — flagged by the IQR rule. What is the best course of action?
C: investigate before changing it.
Yolanda made landfall that month; an extreme reading is plausibly the single most important value in the column. Deleting or capping it produces a "cleaned" dataset in which the storm did not happen.
Statistically unusual and factually wrong are different judgments. Only the first one is automatic.
Every flagged point is inspected before it is treated.
Cleaning changes the results, so it must be documented.
Parts A and B covered dropping, filling, flagging and capping. This part covers recording each of those choices so that others can check them.
"Dropping, filling, capping and removing each change what the dataset can show. Two careful analysts can clean the same file differently and reach different conclusions; either is defensible only if the choices are visible."Cleaning is an early stage of analysis
For this reason, "the data was cleaned" is never sufficient in this course. A report states how, at what cost, and how many rows were affected.
When data is used in journalism, these choices face public scrutiny.
The original file is never overwritten. Cleaned versions are new, derived objects.
Every step is a line of code that can be re-run, not a manual spreadsheet edit that cannot be reproduced.
What was done, why, and how many rows were affected: "filled 2 temps with region means; dropped 1 impossible rainfall."
A notebook satisfies rule 2 by design. Rules 1 and 3 are habits that cost little and make questions such as "where did row 47 go" answerable.
Reproducibility means that another person can rerun the notebook on the raw file and obtain exactly the same cleaned file.
Every decision above changed the row count or a column’s meaning. Unrecorded decisions cannot be reconstructed later, either by the analyst or by a reviewer.
Rows in, rows out and the reason: three numbers and a sentence per step.
log = []an empty list that will collect one entry per cleaning stepdef step(name, before, after, why):define a small function (a reusable recipe) with four inputslog.append({…})add one dict (a dictionary: named values in { }, like a form with labelled boxes) to the list: one row of the logstep("no budget", 34079, 33140, …)record that 939 rows were dropped, and whyAt the start, after each filter and at the end. A loss of 8,000 rows should appear in the log, not be discovered later.
For example, "dropped rows with no budget, because the question is about spending", rather than "cleaned data".
Every step reads data/raw/ and writes data/processed/. The analysis can always restart from the raw data.
If a stranger cannot rebuild the table, the result is not reproducible (someone else cannot rerun it and get the same table), and an irreproducible finding about public money carries no evidential weight.
.isna()null, Python Noneint64, float64, object (text)"n/a" as a numberclip()A small weather frame with gaps, and a series with one suspicious value. The tasks are to count, drop, fill, fence and cap, and to justify each choice in writing. About 45 minutes on the portal’s lab page: fill each ____, press Run, then Check.
isna().sum(), dropna(), fillna(), quantiles and
the IQR fence, z-scores, clip() for capping, duplicates, and
to_numeric(errors="coerce").
Median vs mean on the outlier series, and a groupby().transform() fill that improves on the global mean.
isna().sum() per column, then determine why each gap exists.
Both have a cost. Group-aware fills produce more plausible values.
The IQR rule finds candidates; whether 98 is a typo or a typhoon requires judgment.
Raw data stays unchanged, steps are written in code, and every change has a recorded reason.
In summary: cleaning is a sequence of judgments, each made deliberately, in code and with a recorded reason.
With the data cleaned, next week covers combining, reshaping and reducing it.
pandas User Guide, "Working with missing data": full documentation of
NaN, isna, dropna and fillna.
pandas.pydata.org
Any explanation of Tukey's boxplot and the 1.5×IQR whiskers; about five minutes, and it illustrates Part B's fences.
Both are linked on the course page beside this deck and the lab.
The documentation is easier to follow after the lab.
Integration, transformation and reduction — merging sources, reshaping columns, and reducing large datasets to a manageable size.
DS 227 · Knowledge Discovery in Data