DS 227 · Week 5

Data Preprocessing I

Cleaning, missing data and outliers: deciding what the collected data can support.

Knowledge Discovery in Data · University of the Philippines Cebu

Outline

From raw data to reliable data

Previous session

Collected data is not yet verified data

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.

Meaning of raw data

Nothing guarantees that the values are complete, consistent or even possible.

Limits of modeling

Every later analysis inherits the data's flaws: flawed input yields flawed output, however confident it looks.

This week's two problems

Values that are absent and values that are implausible.

About the tool

NaN was standardised in 1985

Before 1985

Made-up codes

Programmers mark missing values with numbers such as −99999999.

1985

IEEE 754

A floating-point standard adds NaN, “not a number”.

1989

Turing Award

William Kahan, its main architect, receives computing’s highest prize.

Today

pandas

Marks a missing number with numpy.nan.

SourceWikipedia: NaN; William Kahan; pandas: Working with missing data

About the tool

Three behaviours of NaN worth memorising

SourceWikipedia: NaN; outputs from NumPy 2 and pandas 3 on the lecture laptop

Context

Data preparation takes most of the project time

"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
Key terms · 1 of 2

Seven terms for Part A: missing and inconsistent values

missing value

A cell where nothing was recorded. It can mean “unknown”, “not yet” or “refused”.

e.g. an unfinished project has no completion date

NaN

“Not a Number”: how pandas marks an empty cell. Summaries skip it; .isna() finds it.

e.g. df.isna().sum() counts NaNs per column

null

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

imputation

Filling a gap with a chosen stand-in value instead of dropping the row.

e.g. fillna(df.temp.mean())

mean / median / mode

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

duplicate

A row identical to an earlier one. It is counted twice in every total.

e.g. the same project scraped twice

data type

What kind of values a column holds: whole numbers, decimals, text, dates. pandas calls it dtype.

e.g. int64, float64, object (text)

Key terms · 2 of 2

Six terms for Part B: unusual values

outlier

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

quartile

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

IQR

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

standard deviation

The typical distance of values from their mean. A large SD indicates widely spread values.

e.g. s.std()

z-score

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

standardise / normalise

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

Part A

Missing data

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.

Origins

Sources of missing values

First step

Counting missing values per column

isna().sum() is the first check on any new dataset. Per-column counts show where the gaps are; a single total hides this.

Interpreting the counts

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.

df = pd.DataFrame({"city": ["Cebu", "Davao", "Iloilo", "Baguio", "Tacloban"], "temp": [31, np.nan, 33, 29, np.nan], "rain_mm": [12, 4, np.nan, 8, 0]}) print(df.isna().sum()) city 0 temp 2 rain_mm 1 dtype: int64 # and the actual damaged rows print(df[df.isna().any(axis=1)]) city temp rain_mm 1 Davao NaN 4.0 2 Iloilo 33.0 NaN 4 Tacloban NaN 0.0
  • pd.DataFrame({…})a tiny weather table: five cities, three columns; np.nan is an empty cell
  • df.isna()a same-shaped table of True (empty) / False (filled)
  • .sum()adds each column’s Trues (True counts as 1): the gaps per column
  • temp 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”
Case study

The flood control dataset before cleaning

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.

34,079 rows, 15 columns

Real DPWH flood control projects, 2016–2026, in the public domain. Every number on the following slides is computed from exactly this response.

import pandas as pd, requests, io url = "https://portal.latarak.com/api/flood/export.csv" r = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(r.text)) df.shape (34079, 15) # 15 columns, and not one of them is clean
  • 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 door
  • io.StringIO(r.text)hand the downloaded text to pandas as if it were a file
  • df.shape → (34079, 15)34,079 rows (projects) and 15 columns
First step, full dataset

Counting missing values in 34,079 rows

The same one-line check as for the small example, now applied to records of public spending.

Five columns have gaps

The other ten are complete. This is useful to know before any cleaning is planned.

df.isna().sum().sort_values(ascending=False) completion_date 6414 longitude 3195 latitude 3195 start_date 973 contractor 876 description 0 contract_id 0 # … the other 8 columns are 0 too # 18.8% of completion_date is empty
  • .sort_values(ascending=False)sort the counts in descending order, so the columns with the most gaps appear first
  • 64146,414 of 34,079 projects have no completion date: 18.8%
Paired gaps

Latitude and longitude are missing together in 3,195 rows

Diagnosis

Cross-tabulating missingness against a reliable column

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.

Interpretation

If the gap were random, every status would show a similar percentage. The output shows otherwise.

df.groupby("status")["completion_date"].apply( lambda s: s.isna().mean()) status Completed 0.0 For Procurement 1.0 Not Yet Started 1.0 On-Going 1.0 Terminated 0.0 Name: completion_date, dtype: float64
  • 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 between
Result

Missing completion dates are determined by project status

One cause, three columns

Three fields missing before contract award

The 876 For Procurement rows are missing three fields at once, and they are the same 876 rows each time.

Projects before contract award

No contractor has been chosen, no amount agreed, and no completion date is possible. The row is accurate; it records an early stage.

fp = df[df.status == "For Procurement"] len(fp) 876 fp.contractor.isna().sum() 876 (fp.budget == 0).sum() 876 fp.completion_date.isna().sum() 876 # three columns, one cause
  • df[df.status == "For Procurement"]a boolean (True/False) filter: test every row, keep only the rows where the status matches
  • fp.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)
Diagnosis

Random and informative gaps

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

Random glitch

The gap is unrelated to any variable, as with a dropped network packet. Dropping or filling is safest here.

Explained by other columns

Older stations miss more readings. The gap is predictable, so a group-aware fill can work.

The gap is information

High earners skip the income question. Dropping them silently biases every later result, so any treatment must be stated.

Treatment 1

Dropping rows: no invented values, but less data

dropna() invents nothing; it discards rows. The cost is every other value in those rows, which is lost with the gap.

When dropping is acceptable

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.

df = pd.DataFrame( {"region": ["Visayas", "Luzon", "Visayas", "Luzon", "Visayas"], "temp": [31, np.nan, 33, 29, np.nan]}) df.dropna() region temp 0 Visayas 31.0 2 Visayas 33.0 3 Luzon 29.0 ← 5 rows in, 3 rows out
  • 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 unchanged
  • 0, 2, 3the row labels keep their old numbers, which shows that rows 1 and 4 were dropped
Treatment 2

Filling gaps: rows kept, values invented

Filling 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.fillna(df["temp"].mean()) region temp 0 Visayas 31.0 1 Luzon 31.0 ← invented 2 Visayas 33.0 3 Luzon 29.0 4 Visayas 31.0 ← invented
  • df["temp"].mean()the average of the values that exist: (31 + 33 + 29) / 3 = 31.0
  • df.fillna(…)put that number into every empty cell

Limitation

Mean-filling pulls values toward the average and reduces the spread. The more values are filled, the less the column reflects the real data.

Choice of stand-in

Mean, median or mode

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.

Key terms

mean
add everything, divide by how many: (12+45+80+8+12) / 5 = 31.4
median
the middle value once sorted: 8, 12, 12, 45, 80
mode
the most common value (12 appears twice); the only one that works for text

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.

rain = pd.Series([12, 45, np.nan, 80, 8, 12]) print(round(rain.mean(), 1)) print(rain.median()) print(rain.mode()[0]) 31.4 12.0 12.0
  • pd.Series([…])one column of values; np.nan is the gap
  • rain.mean() → 31.4pulled up by the 80: higher than four of the five readings
  • rain.mode()[0]mode() returns a list-like Series (there can be ties); [0] takes the first
Treatment 2, by group

Filling with group means

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

df["temp"] = df["temp"].fillna( df.groupby("region")["temp"] .transform("mean")) df region temp 0 Visayas 31.0 1 Luzon 29.0 ← Luzon mean 2 Visayas 33.0 3 Luzon 29.0 4 Visayas 32.0 ← Visayas mean

Reading the code

transform("mean") builds a column holding each row's group average; fillna then uses it only where values are missing.

Optional extension

The lab asks for this code and an explanation of why it improves on the global mean.

A common shortcut

df.dropna()

It runs instantly and returns a complete frame, but the result is misleading.

Cost

One method call removes 8,709 rows

Dropping every row with any gap produces a tidy table. The row counts show the cost.

25.6% of the dataset

A quarter of the public record is removed without any recorded decision.

clean = df.dropna() len(df), len(clean) (34079, 25370) 34079 - 25370 8709 # 25.6% dropped
  • clean = df.dropna()a new table without any row that had a gap; df keeps all rows
  • len(df), len(clean)two row counts side by side: before and after
Rows removed

Which rows the whole-frame drop removed

df.status.value_counts() status Completed 27534 On-Going 5442 For Procurement 876 Terminated 131 Not Yet Started 96 Name: count, dtype: int64
clean.status.value_counts() status Completed 25274 Terminated 96 Name: count, dtype: int64 # On-Going: GONE # For Procurement: GONE # Not Yet Started: GONE
Conceptual model

dropna() keeps 92% of completed projects and none of the unfinished ones

status df: all 34,079 rows df.dropna(): 25,370 rows kept Completed 27,534 25,274 92% On-Going 5,442 0: every row dropped 0% For Procurement 876 0: every row dropped 0% Terminated 131 96 73% Not Yet Started 96 0: every row dropped 0% 8,709 rows removed (25.6%); 3 of 5 statuses gone entirely
Consequence

After dropping, 99.6% of projects appear complete

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

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.

round(25274 / len(clean), 3) 0.996 # "99.6% completed!" # the real figure, before cleaning round(27534 / len(df), 3) 0.808 # 80.8% # you moved it 19 points by typing # six characters
Guideline

Dropping rows requires a stated reason

Exercise · 8 min

Identifying an informative gap

1 · Load and count

Read the CSV. Run isna().sum(). Identify the column with the most gaps.

2 · Choose a column

Take start_date (973 missing). Cross-tab it against status and against year.

3 · Decide and justify

Decide whether the gap is random or informative. Write a one-sentence footnote that justifies the decision.

4 · Compare

Compare the sentence with a neighbour’s. A disagreement indicates that one of the two has found something.

Review question

Question (select to reveal the answer)

Running df.dropna() on the flood data removes 8,709 rows. What has happened to the analysis?

A · A random quarter of rows was removed, so percentages are unchanged
B · Every unfinished project was removed, so the data now describes only completed work
C · Only rows with typos were removed
D · Nothing important — 25% is a normal loss
B. Missingness tracked status exactly: On-Going, For Procurement and Not Yet Started are 100% missing a completion date, so all of them were dropped. The survivors say 99.6% of projects are complete; the true figure is 80.8%.
Review question

Question (select to reveal the answer)

A survey's income column is 35% empty, and high earners are suspected of skipping it. Should it be filled with the column mean?

A · Yes — mean fill keeps all the rows
B · No — the gaps aren't random; a mean fill biases income downward
C · Yes, but round to the nearest peso
D · Drop the whole column silently

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.

Further check 1

Duplicates: the same row counted twice

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.

The flood data has no duplicates

There are no repeated rows and no repeated contract ids. The check takes one line and prevents double-counting.

t = pd.DataFrame({"city": ["Cebu", "Davao", "Cebu"], "temp": [31, 30, 31]}) print(t.duplicated().tolist()) print(len(t.drop_duplicates())) [False, False, True] 2 # the flood data print(df.duplicated().sum()) print(df.contract_id.duplicated().sum()) 0 0
  • 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 out
  • df.contract_id.duplicated()repeats in one column only: a contract id should never appear twice
Further check 2

Every column has a data type

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

Reading the output

float64
numbers with decimals (budgets in pesos and centavos)
int64
whole numbers (the year)
object
pandas’ word for text

Dates stored as text

start_date looks like 2022-07-14 but is stored as text: two dates cannot be subtracted until the column is converted.

print(df[["budget", "year", "start_date", "status"]].dtypes) budget float64 year int64 start_date object status object dtype: object
  • df[[…]]keep four columns (a list of names inside the brackets)
  • .dtypesthe data type of each column
Reading an error

When a number column contains “n/a”

pd.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 call

Solution

errors="coerce" turns anything unreadable into NaN instead of stopping: the bad cell becomes a missing value that can be counted, as in Part A.

import pandas as pd raw = pd.Series(["31", "n/a", "33"]) nums = pd.to_numeric(raw) Traceback (most recent call last): File "clean.py", line 3, in <module> nums = pd.to_numeric(raw) … pandas’ own inner lines (trimmed) … ValueError: Unable to parse string "n/a" at position 1 nums = pd.to_numeric(raw, errors="coerce") print(nums.tolist()) [31.0, nan, 33.0]
Break

  Five minutes

Next: values that are present but implausible.

Part B

Outliers

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.

Definition

An outlier is a point far from the rest

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

s = pd.Series( [12, 14, 13, 15, 11, 14, 98, 13, 12]) ↑ this one

Two possible explanations

A data-entry error (9.8 typed as 98) or a real reading from an extreme day. The same number has opposite meanings.

Two stages

Flagging is mechanical (this part); judging requires inspection (the next part).

Standard method

The IQR rule and its fences

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.

q1, q3 = s.quantile(0.25), s.quantile(0.75) iqr = q3 - q1 low = q1 - 1.5 * iqr high = q3 + 1.5 * iqr s[(s < low) | (s > high)] 6 98 ← flagged dtype: int64
  • s.quantile(0.25), s.quantile(0.75)Q1 = 12.0 and Q3 = 14.0 for this series
  • iqr = q3 - q114 − 12 = 2: the width of the middle half
  • low, highfences at 12 − 3 = 9.0 and 14 + 3 = 17.0
  • (s < low) | (s > high)below the low fence or (|) above the high one
  • 6 98row label 6 holds the value 98: the only point past a fence

Reason for using quartiles

Quartiles barely change when an extreme value appears, so the fence is not distorted by the point it is meant to detect.

Note

The 1.5 multiplier is a convention

"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
Alternative method

A z-score counts standard deviations

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

Reason IQR remains the default

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.

z = (s - s.mean()) / s.std() print(round(s.mean(), 2), round(s.std(), 2)) print(z.round(2).tolist()) print(s[z.abs() > 2].tolist()) 22.44 28.36 [-0.37, -0.3, -0.33, -0.26, -0.4, -0.3, 2.66, -0.33, -0.37] [98]
  • s - s.mean()each value’s distance from the mean (22.44)
  • / s.std()measured in standard deviations (28.36) instead of in millimetres
  • z.abs() > 2abs drops the minus sign; keep values more than 2 SDs away, either side
  • 2.66the 98 is 2.66 SDs above the mean; every other value is within half an SD
Judgment

A flag marks a value for inspection, not deletion

Three treatments

Keep, cap or remove: a deliberate choice

Robustness

The mean is sensitive to outliers; the median is not

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.

round(s.mean(), 2) 22.44 ← dragged up by the 98 s.median() 13.0 ← what a typical value looks like

Guideline

When outliers are suspected, report the median and use it for filling. A large gap between mean and median is itself a finding.

Case study

Distribution of the budget column

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.

Skewed but valid

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.float_format", "{:,.0f}".format) print(df.budget.describe()) count 34,079 mean 46,952,340 std 48,594,319 min 0 25% 14,649,406 50% 37,676,233 75% 67,549,270 max 1,447,499,996 Name: budget, dtype: float64 # max is 38x the median
  • pd.set_option(…)display setting: show numbers with commas and no decimals
  • .describe()an eight-number summary: count, mean, SD, smallest, quartiles, largest
  • 25% / 50% / 75%Q1, the median, Q3
IQR on the full dataset

IQR applied to 34,079 real contracts

The formula is the same as in the small example; the result is now a peso amount of public interest.

798 projects flagged

2.34% of the dataset sits above the upper fence. These rows are for inspection, not deletion.

q1, q3 = df.budget.quantile([.25, .75]) iqr = q3 - q1 fence = q3 + 1.5 * iqr print(round(q1), round(q3), round(iqr), round(fence)) 14649406 67549270 52899864 146899067 (df.budget > fence).sum() 798
  • quantile([.25, .75])both quartiles at once: about ₱14.6M and ₱67.5M
  • fenceQ3 + 1.5 × IQR: about ₱146.9M
  • (df.budget > fence).sum()how many budgets are above it: 798
Inspection

The three largest budgets are not errors

BudgetRegionDescription
₱1,447,499,996Central OfficeConstruction of small river impounding project
₱1,096,255,230Central OfficeConstruction of bank protection works
₱1,042,782,802Central OfficeConstruction of bank protection works
Mean and median

Mean and median budgets differ by 25%

The mean is pulled upward by the same 798 projects the fence flagged. The median does not move.

Reporting skewed amounts

"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()) 46952340 round(df.budget.median()) 37676233 round(46952340 / 37676233, 2) 1.25 # mean is 25% higher
  • round(df.budget.mean())the average budget, rounded to whole pesos: about ₱47.0M
  • round(df.budget.median())the middle budget: about ₱37.7M
  • 1.25the mean is 1.25 times the median, i.e. 25% higher
Placeholder values

939 projects with a budget of exactly zero

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

Same cause as the missing dates

876 are For Procurement. The remaining 63 are Terminated. Both are "no money moved", recorded as 0 rather than as blank.

z = df[df.budget == 0] len(z) 939 z.status.value_counts() status For Procurement 876 Terminated 63 Name: count, dtype: int64 # 0 here means "not applicable", # NOT "free"
Placeholder values

Interpreting placeholders before averaging

Exercise · 6 min

Flagging and inspecting budgets

1 · Flag by region

Compute the IQR fence within each region instead of across the whole country. Does Region III flag different projects?

2 · Read three

Open the descriptions of any three flagged rows. Do they look like errors or like large projects?

3 · Decide

Choose keep, cap or remove, and write the reason next to each.

Hint

df.groupby("region").budget.transform(lambda s: s.quantile(.75) + 1.5*(s.quantile(.75)-s.quantile(.25)))

Review question

Question (select to reveal the answer)

939 flood projects have budget == 0. Should they be included when computing the average project budget?

A · Yes — zero is a real number and dropping it is cherry-picking
B · No — they are 'For Procurement' or 'Terminated'; 0 means not applicable, not free
C · Yes, but only if the outliers are also dropped
D · It makes no difference at this sample size
B. All 939 are projects with no awarded contract (876 For Procurement) or a cancelled one (63 Terminated). Including them answers an irrelevant question: the cost of a contract that does not exist.
Review question

Question (select to reveal the answer)

Daily rainfall for Tacloban, November 2013. One day reads 600 mm — flagged by the IQR rule. What is the best course of action?

A · Remove it — the rule flagged it
B · Cap it to the fence value
C · Check the date against events — it may be Typhoon Yolanda, i.e. real
D · Replace with the November mean

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.

Part C

Documenting cleaning decisions

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.

Principle

Cleaning consists of decisions about the data

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

Three rules that make cleaning auditable

Reproducibility

A cleaning log kept in code

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.

Row counts at every step

Rows in, rows out and the reason: three numbers and a sentence per step.

# cleaning log — keep it in the notebook log = [] def step(name, before, after, why): log.append({"step": name, "dropped": before - after, "why": why}) step("no budget", 34079, 33140, "cannot answer a spend question")
  • log = []an empty list that will collect one entry per cleaning step
  • def step(name, before, after, why):define a small function (a reusable recipe) with four inputs
  • log.append({…})add one dict (a dictionary: named values in { }, like a form with labelled boxes) to the list: one row of the log
  • step("no budget", 34079, 33140, …)record that 939 rows were dropped, and why
Audit

Rebuilding the table from the notebook

Glossary

Terms introduced in Part A

Missing data

missing value
a cell where nothing was recorded
NaN
pandas’ empty-cell marker; find it with .isna()
null
“no value” in general: JSON null, Python None
missing at random
gaps that fall anywhere, unrelated to other columns
structural gap
a gap caused by how the data was built
cross-tab
one column’s pattern broken down by another’s groups
survivorship bias
conclusions drawn only from the rows that survived a filter
placeholder
a value typed in to fill a slot, e.g. a budget of 0

Treatments and tools

imputation
filling a gap with a chosen stand-in value
mean / median / mode
average / middle value / most common value
group mean
the average within a group, e.g. per region
duplicate
a row identical to an earlier one
data type
what a column holds: int64, float64, object (text)
ValueError
right kind of input, unusable value, e.g. "n/a" as a number
errors="coerce"
turn unconvertible values into NaN instead of stopping
lambda
a tiny one-line function with no name
Glossary

Terms introduced in Parts B–C

Outliers

outlier
a value far from the others; not necessarily wrong
quartile
cut points splitting sorted data into four equal groups
IQR
Q3 − Q1; fences sit 1.5 IQRs beyond the box
standard deviation
typical distance of values from the mean
z-score
distance from the mean, in standard deviations
standardise / normalise
rescale to z-scores / into the range 0 to 1

Judging and recording

skewed
a few very large values stretch one side, e.g. budgets
capping (winsorizing)
pull extremes in to the fence with clip()
leverage
one value’s power to move a result
robust
barely moved by extremes: the median is, the mean is not
cleaning log
rows in, rows out and the reason, for every step
reproducible
someone else can rerun it and get the same table
This week's lab

Missing values and an outlying 98

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.

Lab tasks

isna().sum(), dropna(), fillna(), quantiles and the IQR fence, z-scores, clip() for capping, duplicates, and to_numeric(errors="coerce").

Optional extension

Median vs mean on the outlier series, and a groupby().transform() fill that improves on the global mean.

Summary

Four main points

Readings

Preparation for next week

Next week

Data preprocessing II

Integration, transformation and reduction — merging sources, reshaping columns, and reducing large datasets to a manageable size.

DS 227 · Knowledge Discovery in Data