ACOL2010 Data Science, Module 2 — Lectures 11 to 14, rewritten as one guide

Data cleaning and preprocessing

Before a table can answer a question, you have to know what its columns mean, look at what is actually in it, decide what to do about the entries you cannot trust, and put numeric columns on comparable scales. This page teaches all four steps, in order, with the two examples the lectures keep returning to.

Twelve salaries, in thousands of dollars. Almost every idea in Parts 2 and 4 is demonstrated on these twelve numbers: their mean (58) and median (54), their quartiles, the fence that flags 110, their standard deviation, and their rescaled versions.

Where this module sits

The course follows a data pipeline. Module 2 is the Clean stage: everything that has to happen after data are stored and before they can be trusted for understanding or prediction.

CollectStoreCleanUnderstandPredictUse

The four lectures form a single argument, and this page keeps their order:

  1. What do the columns mean? (Lecture 11) A column's stored type (integer, float, text) does not say what it represents. You need metadata to know which calculations make sense.
  2. What is actually in the table? (Lecture 12) Profile it systematically, describe the centre and spread of numeric columns, and flag unusual values — without repairing anything yet.
  3. What do we do about entries we cannot trust? (Lecture 13) Name what kind of unknown each entry is, ask how it became unknown, choose a treatment knowing what it assumes, and write the decision down.
  4. How do we compare columns on different scales? (Lecture 14) Measure spread with the standard deviation, rescale by range (min–max) or by standard deviation (z-score), and record exactly what was used.

One principle runs through all four: the data alone rarely tell you what to do; knowledge of how they were collected does. Every lecture ends with some version of “detect, record, and ask”.

The two running examples

The patient file

A researcher sends a file with no description beyond “each line is a patient; predict the last value”. First rows:

field 1field 2field 3field 4field 5
01223233.5010.7
02012116.92210.1
02716524.00427.6

Facts revealed later: field 1 is a patient ID; field 4's valid values are 1 to 10 with 0 meaning “missing”; and a data-entry error turned every 10 in field 4 into 0.

The twelve salaries

In thousands of dollars, already sorted:

30 36 47 50 52 52 56 60 63 70 70 110

Sum 696, so the mean is 58. Used for centre and spread (Part 2), the outlier rule (Part 2), the standard deviation (Part 4) and both rescaling methods (Part 4).

Boxes with a dashed border, headed Beyond the lecture, add depth that the slides assumed or skipped. Read them for understanding; the core of each section is what the lectures examined.

Part 1, from Lecture 11

What the columns mean: attribute types and data quality

Central question: what do the columns mean, and which comparisons and summaries are meaningful? By the end of this part you should be able to classify an attribute by what its values represent, justify the summaries that suit it, and judge whether data are suitable by first stating the use they must serve.

1.1From SQL to pandas

Module 1 stored data in a database and queried it with SQL. From here on we analyse tables in Python with pandas. Three tools are involved:

  • SQLite is the database engine: it stores tables in a single file (here demo.db) and runs SQL queries. Python's built-in module sqlite3 lets Python talk to it.
  • pandas is a Python library for inspecting, cleaning, transforming and analysing tabular data. By convention it is imported as pd.
  • A DataFrame is pandas' table: two-dimensional, held in memory in your Python session, with labelled rows (the index) and labelled columns. Each row is a record (one object, such as a patient) and each column is an attribute. The name df is just a conventional variable name, not a keyword.

Suppose a SQLite table Data has one column Attr, declared INTEGER, holding 1, NULL and 3. Loading the result of a query into pandas looks like this:

Python
import sqlite3
import pandas as pd

conn = sqlite3.connect("demo.db")       # an open link to the database file
sql = "SELECT Attr FROM Data"            # the query, as a string
df = pd.read_sql_query(sql, conn)        # run it; the result becomes a DataFrame

print(df)
print(df.dtypes)          # how each column is stored
print(df.isna().sum())    # how many entries pandas recognises as missing, per column
   Attr
0   1.0
1   NaN
2   3.0
Attr    float64
dtype: object
Attr    1
dtype: int64

Four things in that output need explaining.

  • The 0, 1, 2 on the left are the row index that pandas assigns. They are labels, not data.
  • SQL NULL became NaN (“not a number”), which is pandas' default marker for a missing number.
  • The column is float64, not an integer type, so 1 and 3 print as 1.0 and 3.0. The reason is below.
  • isna() produces a True/False table marking each recognised missing entry; .sum() counts the Trues per column (True counts as 1). Here: one.

Beyond the lecture: why a missing value turns integers into floats

A 64-bit integer (int64) uses all 264 bit patterns for actual integers, so there is no pattern left over to mean “missing”. Floating-point numbers (IEEE 754 float64) reserve special patterns, including NaN. So when a column of integers contains a gap, pandas' default behaviour is to convert the whole column to float64 and use NaN for the gap.

pandas also has nullable types that store a separate “is missing” mask beside the values, so integers can stay integers. The marker then prints as <NA>:

Python
df2 = pd.read_sql_query(sql, conn, dtype_backend="numpy_nullable")
print(df2); print(df2.dtypes)
   Attr
0     1
1  <NA>
2     3
Attr    Int64
dtype: object

Note the capital I in Int64: that is the nullable type. Either way, isna() recognises only pandas' own markers (NaN, None, <NA>, NaT for dates). A code such as 0 or −9999 that means missing is, to pandas, an ordinary number. This becomes important in Parts 2 and 3.

Finally, df is a copy held in Python. Changing it does not change the database.

Loading preserves the missing entry, but it does not establish what the values mean or whether they are fit for an analysis.

1.2Metadata: why the digits are not enough

Look again at the patient file. Each “field” is a column. What must an analyst know before using these columns?

The digits themselves cannot tell you:

  • whether a column identifies patients, records a category, or measures a quantity (is 012 a code or the number twelve?);
  • what unit a measurement is in (is 33.5 kilograms, a percentage, a temperature?);
  • whether a value such as 0 is a real measurement or a code, for example for “not measured”.

Metadata is data about the data: what each column represents, its unit, and its coding conventions (including any code for a missing measurement). Documentation explains the metadata and may also describe how the data were collected and processed.

The two overlap but are not exact synonyms, and neither guarantees that the data are correct.

A column's stored data type does not tell us what its values mean. That is why we need documentation.

1.3Meaning versus storage

Employee ID and age can both be stored as integers, and software will happily average either. Would both averages tell you something?

Average age describes the employees. Average ID does not: IDs are labels, and if the company reassigned every ID, the “average ID” would change while nothing about any employee changed. A calculation is only meaningful if its result depends on the property, not on the arbitrary way the property was written down.

Five terms keep these layers apart. Read the table top to bottom: it goes from the thing in the world to the bits in the computer.

TermQuestion it answersEmployee example
ObjectWhich entity is described?an employee
AttributeWhat property is represented?the employee's age
Measurement scaleHow is that property turned into a value?count completed years since birth
Recorded valueWhat was entered for this particular object?the number entered for this employee, e.g. 34
Stored data typeHow does software represent the entry?an integer (SQL INTEGER; pandas int64)

The attribute and measurement scale explain what the values mean. The stored type explains how software holds them. A stored type determines which operations software can run; meaning determines which results you can interpret.

1.4Attribute types

Attribute types classify what the values represent, so that we can decide which comparisons and summaries are meaningful. The classification (from Han, Pei and Tong) is:

Attribute Nominal Ordinal Numeric Binarynominal, two states Interval-scaled Ratio-scaled ordered categories,gap sizes unknown ← categories, no order
Binary is a special case of nominal. Numeric splits by whether zero is arbitrary (interval) or means “none of it” (ratio). These are types of meaning; INTEGER, int64 and float64 are types of storage. Documentation supplies meanings, units and codes, but often does not name the type: the analyst classifies the attribute from that information.

Nominal

A nominal attribute's values are names of categories or states, with no meaningful order. Examples: hair colour (black, brown, blond, red, auburn, grey, white); marital status (single, married, divorced, widowed). Numbers can serve as nominal labels: a customer ID or a zip code. Subtracting two customer IDs or adding two zip codes measures nothing, because the digits only name.

  • Meaningful comparison: same category or different.
  • Meaningful summaries: the count (frequency) of each category, and the mode, the most frequent category.

An average hair colour or an average zip code describes nothing.

Binary

A binary attribute is nominal with exactly two states, often coded 0 and 1. Examples: smoker (1 = smokes, 0 = does not); a medical test (1 = positive, 0 = negative). The codes are labels, not quantities.

Meaningful summaries are the count of each state and the proportion in each state. There is one useful coincidence: the mean of a 0/1 column equals the proportion of 1s (five smokers among 20 patients: the mean of the column is 5/20 = 0.25, the share who smoke). That is the only meaningful reading of such a mean.

Beyond the lecture: symmetric and asymmetric binary

Han distinguishes symmetric binary attributes, where both states are equally informative (e.g. a 0/1 code for two equally common categories), from asymmetric ones, where one outcome is rare and more important, such as a positive test for a rare disease. By convention the important outcome is coded 1. The distinction matters later when measuring similarity between objects: two patients who both tested negative are not thereby “similar” in any interesting way.

Ordinal

An ordinal attribute has values with a meaningful order, but the size of the difference between successive values is unknown. Drink size small < medium < large: large is bigger than medium, but not by a known amount. Customer satisfaction coded 1 (very dissatisfied) to 5 (very satisfied): the codes record order; they do not establish that the step from 1 to 2 equals the step from 4 to 5.

  • Meaningful comparisons: same or different; before or after in the order.
  • Meaningful summaries: counts per level, the mode, and the median (the middle value once the values are put in order).
A mean of ordinal codes assumes equal gaps that the scale does not provide.

Numeric: interval-scaled

A numeric attribute is a measurable quantity, recorded as an integer or real number. It is interval-scaled or ratio-scaled.

An interval-scaled attribute is measured in equal-size units, so differences are meaningful, but its zero is an arbitrary reference point. Temperature in °C: 20 °C is five degrees warmer than 15 °C, but 0 °C does not mean “no temperature”, so 10 °C is not “twice as warm” as 5 °C. Calendar year: 2012 and 2020 are eight years apart, but year 0 is not the beginning of time.

Meaningful summaries: the mode, the median and the mean. Equal units are what make averaging meaningful.

Numeric: ratio-scaled

A ratio-scaled attribute is numeric with an inherent zero: zero means none of the quantity. Both differences and ratios are meaningful. Examples: elapsed time (0 s means no time has passed, so 10 s is twice as long as 5 s); counts such as years of experience or the number of words in a document; weight, height, money; temperature in kelvin (0 K is where thermal motion ceases in the classical picture, so a ratio of kelvin readings compares absolute temperatures, though not how warm conditions feel).

Meaningful summaries: everything allowed for interval attributes, plus ratio statements such as “twice as long” or “100 times as much money”.

On an interval scale, differences are meaningful. On a ratio scale, ratios are too.

1.5Why the rules are what they are

The lists of “meaningful summaries” above can look like arbitrary rules to memorise. They are not. They all follow from one test.

Beyond the lecture: the relabelling test (Stevens' levels of measurement)

Every attribute was written down using some choice of labels or units that could have been made differently without changing the facts. A statement is meaningful only if its truth survives every such allowable re-description. What counts as allowable depends on the type:

TypeAllowable re-descriptionsWhat survives them
Nominalany one-to-one relabelling (reassign all IDs; rename colours)“same / different” only, hence counts and mode
Ordinalany order-preserving recoding (1–5 could just as well be 1, 2, 3, 10, 100)order, hence median; not means
Intervalchange of unit and zero point: x → a·x + b, a > 0 (°C → °F is F = 1.8C + 32)order, and ratios of differences; hence means; not ratios of values
Ratiochange of unit only: x → a·x, a > 0 (m → cm, kg → lb)everything above plus ratios of values

Why a mean of ordinal codes misleads. Two shops each get two satisfaction ratings. Shop A: 1 and 5. Shop B: 3 and 3. With codes 1–5 both means are 3, “equally satisfied”. But the codes only promise order, so recoding 5 as 10 is just as faithful to the data. Now shop A's mean is 5.5 and B's is 3: the conclusion flipped, because it depended on the arbitrary gap sizes. The medians, by contrast, depend only on order.

Why “twice as warm” fails in °C. Try it below: a ratio of Celsius readings changes when you switch to Fahrenheit, so it was never a fact about the weather. A ratio of kelvin readings is stable under unit changes, because kelvin has a true zero.

Is 10 °C “twice as warm” as 5 °C?

Enter two temperatures in °C. A statement that is a real fact about the weather should not depend on the unit.

1.6Discrete and continuous

This is a separate distinction that applies on top of the types above; it is not a fifth type.

  • A discrete attribute has a finite or countably infinite set of possible values. Finite: hair colour, smoker, drink size. Countably infinite (you can list them 1, 2, 3, … forever): customer ID, zip code, number of words in a document.
  • A continuous attribute is not discrete: its values can lie anywhere in a continuum, such as height or weight. In practice a computer stores them with finitely many digits, but the quantity itself is continuous.

Nominal and binary attributes are always discrete; numeric ones can be either. How you record something matters: time since birth is continuous, but age recorded in completed years is discrete.

Discrete versus continuous is not the same as integer versus float storage. A continuous height stored as a whole number of centimetres is still a continuous attribute; a count stored as float64 (because of a NaN) is still discrete.

1.7Types at a glance

TypeValues representMeaningful comparisonsSummaries
Nominalcategory names, no ordersame / differentcounts, mode
Binarytwo statessame / differentcounts, proportions
Ordinalordered categories, gap sizes unknown+ ordercounts, mode, median
Intervalequal units, arbitrary zero+ differencesmode, median, mean
Ratioequal units, inherent zero+ ratiosmode, median, mean, ratio statements

Read the comparisons first: a median needs order; a mean needs equal units. The type decides which summaries are legitimate; the question being asked, and how the values are spread, decide which legitimate summary is most useful (Part 2).

Check yourself: classify and summarise

For each attribute, give its type and a meaningful summary, and say why. Does recording values as numbers make every numerical summary meaningful?

  1. an employee's ID
  2. an employee's age in years
  3. customer satisfaction, coded 1 = very dissatisfied to 5 = very satisfied
  4. outdoor temperature in °C
Show answers
TypeA meaningful summaryWhy
(a) IDnominalthe number of employeesIDs are labels. Checking that every ID is distinct is a data check, not a summary of employees.
(b) agenumeric, ratiomean or median ageequal units and an inherent zero
(c) satisfactionordinalcount per level; mode or median levelcodes record order, not equal gaps
(d) °Cnumeric, intervalmean or median temperatureequal units; ratios of readings are not meaningful

No. Numbers can be labels, as in (a), or ordered codes, as in (c). A numerical summary is meaningful only if the attribute type supports it.

1.8Data quality: fit for which use?

Knowing what a column means does not guarantee that its values can answer your question. Two situations:

  • A manager wants to compare sales of items advertised as on sale with those that were not, but advertising status was never recorded.
  • Sales staff need to interpret company records but do not understand the accounting codes.

Neither task can be completed: data must contain the required information and be understandable to the people using them.

Data have quality when they satisfy the requirements of their intended use. Quality is not a property of a table on its own; it is a relationship between a table and a purpose.

Six dimensions make those requirements concrete:

DimensionQuestionExample of a failure
AccuracyAre the recorded values correct?some customer addresses are outdated or wrong
CompletenessIs the information needed for the task recorded?no advertising status, so advertised and unadvertised items cannot be compared
ConsistencyDo records agree in their conventions?department codes used differently in different records
TimelinessIs the information available and current when needed?sales records arriving after bonuses are decided are too late for that decision
BelievabilityDo users regard the data as credible?staff distrust data that had errors in the past, even after they were corrected
InterpretabilityCan users understand the values?accurate accounting codes that are useless without their meanings

Check yourself: who is right?

A marketing analyst needs customer addresses for target marketing. About 80% are accurate, and she is pleased. The sales manager, analysing the branch's sales from the same database, finds it inaccurate. Which judgement is correct, and what must you know before calling the database good?

Show answer

Both can be valid, because each is made against a different intended use. For mass marketing, 80% deliverable addresses may be good enough. The manager's analysis has different requirements, and against those the same data fall short.

The 80% figure is acceptable only for that marketing use; it is not a general threshold for “good data”. Before calling a dataset good, state its intended use and how accurate, complete and current that use requires it to be.

Reading: Han, Pei and Tong, Data Mining: Concepts and Techniques §2.1, §2.4. Tan, Steinbach, Karpatne and Kumar, Introduction to Data Mining ch. 2, §2.1.1, §2.2. Badia, SQL for Data Science §1.1, §1.3, §6.2.

Part 2, from Lecture 12

Profiling a table, describing it, and flagging what looks unusual

Lecture 11 was about what columns mean. This part is about what is in them. By the end you should be able to read a first profile of a table and record possible problems without repairing anything; describe the centre and spread of a numeric attribute with the mean, median, quartiles and interquartile range; and flag potential outliers with the 1.5 × IQR rule while explaining what a flag does not establish.

2.1Data profiling

Back to the patient file. We are now told that field 1 holds identification numbers. So field 1 identifies patients; it does not measure anything about them. Which summaries of field 1 are meaningful? A mean of field 1 describes nothing. The meaningful checks are how many patients there are and whether any identifier repeats. What a column identifies decides which checks make sense.

Data profiling is the systematic examination and summary of a dataset's structure and recorded values, carried out to identify possible problems before any change is made.

A profile answers six questions. The first five are answered from the data; the sixth needs the metadata.

Profile questionWhat answers it
1. How many rows, and which columns?displaying the DataFrame; df.shape
2. How is each column stored?df.dtypes
3. How many entries does pandas recognise as missing?df.isna().sum()
4. What is the range of each numeric column?df.describe(): its count, min and max rows
5. Which values occur, and how often?df["field4"].value_counts()
6. Which rules must the values obey?the documentation, written down in words

Here is the profile of the three printed rows. The file is read from text; dtype={"field1": str} tells pandas to keep field 1 as text, for a reason explained just after.

Python
import io
import pandas as pd

csv = """field1,field2,field3,field4,field5
012,232,33.5,0,10.7
020,121,16.9,2,210.1
027,165,24.0,0,427.6"""
df = pd.read_csv(io.StringIO(csv), dtype={"field1": str})

print(df.dtypes)
print(df.isna().sum())
print(df["field4"].value_counts())
print(df.describe().loc[["count", "min", "max"]])
field1        str
field2      int64
field3    float64
field4      int64
field5    float64
dtype: object

field1    0
field2    0
field3    0
field4    0
field5    0
dtype: int64

field4
0    2
2    1
Name: count, dtype: int64

       field2  field3  field4  field5
count     3.0     3.0     3.0     3.0
min     121.0    16.9     0.0    10.7
max     232.0    33.5     2.0   427.6

Reading this output:

  • Field 1 is stored as text (pandas 3 prints str; older versions print object), so describe(), which summarises numeric columns, leaves it out. That is correct for an identifier.
  • No entries are recognised as missing. That does not show that every measurement was recorded: pandas recognises only its own markers, and field 4's zeros are ordinary integers to it.
  • Field 4 has minimum 0, and the value 0 occurs twice. The documentation (received later) says field 4's valid values are 1 to 10 and 0 is the missing-value code. So this is the profile raising a question, not answering it.

Rules to record in words: the field-4 rule (valid 1–10; 0 = missing), and “field 1 values must be distinct”, because it is an identifier.

Beyond the lecture: what happens if you let pandas guess field 1's type

Python
bad = pd.read_csv(io.StringIO(csv))     # no dtype given
print(bad["field1"].tolist(), bad["field1"].dtype)
print(df["field1"].is_unique)           # the identifier check, on the text version
[12, 20, 27] int64
True

Left to guess, pandas reads 012 as the number 12 and the leading zero is gone for good. If another system stores the ID as the text “012”, the two will no longer match. Identifiers (IDs, zip codes, phone numbers) should be read as text: that both preserves their written form and stops software from offering numeric summaries of them.

2.2What a profile can and cannot establish

A profile establishes how columns are stored, which entries pandas recognises as missing, and each column's range and value counts. It cannot establish what a value means, whether it is correct, or what to change. Those need metadata and knowledge of how the data were collected. A profile raises questions; it does not choose repairs.

The questions it raises fall into four kinds of suspected problem:

Suspected problemMeaningExample
Missing valuean attribute value that was not recorded, whether left empty or marked by a codefield 4 = 0, if 0 is the missing code
Noisy or outlying valueNoise is random measurement error. An outlier is unusual for its attribute but may be perfectly correct.a height of 7.5 feet: an error in a school register, but plausible in a basketball team
Inconsistent valueconflicts with another value, a rule, or a coding conventiona birth date after the admission date; “M” in one file and “male” in another
Duplicaterecords that appear to represent the same object at the level one row is meant to describethe same patient entered twice. But two distinct people with the same name are not duplicates.

Check yourself: interpreting the profile

The profile of the three rows reported no entries recognised as missing, a minimum of 0 for field 4 with the value 0 twice, and no summary of field 1. The documentation says field 4's valid values are 1 to 10, and 0 is the missing-value code.

  1. Is field 4 complete?
  2. Field 1 was not summarised. Is that a problem, and what should be checked instead?
  3. State one rule to record and one action not to take yet.
Show answers
  1. No, according to the documentation. isna() counts only pandas markers such as NaN; the zeros are ordinary integers, so the count is 0. But two of the three entries are the documented missing code.
  2. Not a problem. Field 1 is an identifier, so a mean would be meaningless. Check instead that its values are distinct and keep their written form, such as 012.
  3. Record the field-4 rule. Do not yet replace the zeros, delete rows, or drop field 1.

Then the later information arrives: a data-entry error changed every 10 in field 4 into 0. Each zero may be a missing measurement or a corrupted 10, so the table alone cannot even say how many measurements are missing.

Detect, record and ask. The repair needs information that this file does not contain.

2.3Centre: the mean and the median

The profile's count, min and max describe size and range. Descriptive statistics go further: they help us grasp what the values are like and spot unusual ones. We switch to the twelve salaries to ask three questions: what is a typical salary? how much do salaries vary? which ones deserve a closer look?

The mean is the sum of the values divided by their number: x̄ = (x1 + x2 + … + xN) / N. For the salaries, 696 / 12 = 58.

The median is the middle value of the ordered list. With an even count it is the average of the two middle values. Here the 6th and 7th values are 52 and 56, so the median is (52 + 56) / 2 = 54.

The mean sits to the right of the median: the single value 110 pulls it up. The median only cares which values are in the middle.

The two respond to values differently. The mean depends on the magnitude of every observation. The median depends only on the middle ordered value(s): make 110 into 1,000 and the median stays 54 while the mean jumps to about 132. The gap between mean (58) and median (54) is a first clue that something is pulling the mean.

Check yourself: which moves more?

Without the 110, the list has eleven salaries: 30, 36, 47, 50, 52, 52, 56, 60, 63, 70, 70. Predict before calculating: when 110 is added, which moves further, the mean or the median? Roughly how far?

Show answer
MeanMedian
Eleven values (no 110)586 / 11 ≈ 53.36th value = 52
Twelve values5854
Change≈ +4.7+2

The mean moved more than twice as far. Does that make the median the better summary? Not automatically: choose by the question. The median suits “what does a typical employee earn?” when a few values are extreme. The mean answers questions about totals: 12 × 58 = 696 is the payroll. No median can tell you that.

Beyond the lecture: what each centre is best at

The mean is the balance point: the deviations above it exactly cancel those below it (you will use this in Part 4). It is also the single number that minimises the sum of squared distances to the data. The median minimises the sum of absolute distances. Squaring makes far-away points count heavily, which is exactly why one extreme value drags the mean and barely touches the median. Statisticians call the median robust to extreme values.

2.4Quartiles and the five-number summary

The median splits the ordered data in half. Quartiles split it in quarters: Q1, the median and Q3 are the 25th, 50th and 75th percentiles (a pth percentile is a value with about p% of the data at or below it). With twelve values, four groups of three show where they fall:

Q1 falls between 47 and 50, the median between 52 and 56, Q3 between 63 and 70.

But where exactly between them? There are several conventions. The lecture uses pandas' default, called linear interpolation, which gives Q1 = 49.25, median = 54, Q3 = 64.75. Here is how it works, because the slides only stated the numbers:

  1. Number the sorted values from position 0 to N − 1 (here 0 to 11).
  2. The p-quantile sits at position (N − 1) × p.
  3. If that position is fractional, go that fraction of the way from the value below to the value above.
Position (N − 1) pNeighboursValue
Q1 (p = 0.25)11 × 0.25 = 2.75pos 2 = 47, pos 3 = 5047 + 0.75 × (50 − 47) = 49.25
Median (p = 0.5)11 × 0.5 = 5.5pos 5 = 52, pos 6 = 5652 + 0.5 × 4 = 54
Q3 (p = 0.75)11 × 0.75 = 8.25pos 8 = 63, pos 9 = 7063 + 0.25 × 7 = 64.75
Python
s = pd.Series([30, 36, 47, 50, 52, 52, 56, 60, 63, 70, 70, 110], name="salary")
print(s.describe())

# other conventions give other quartiles for the same data
for m in ["linear", "lower", "higher", "midpoint", "nearest"]:
    print(m, s.quantile([0.25, 0.75], interpolation=m).tolist())
count     12.000000
mean      58.000000
std       20.338052
min       30.000000
25%       49.250000
50%       54.000000
75%       64.750000
max      110.000000
Name: salary, dtype: float64
linear [49.25, 64.75]
lower [47, 63]
higher [50, 70]
midpoint [48.5, 66.5]
nearest [50, 63]

So a textbook or calculator might report Q1 = 48.5 and Q3 = 66.5 for the very same list. Neither is wrong; state which convention you used, and use the same one throughout. (Notice describe() also prints a std row: 20.34. That is a standard deviation computed with a divisor of N − 1. Part 4 explains it, and why the course uses 19.47 instead.)

The five-number summary is minimum, Q1, median, Q3, maximum. For the salaries: 30, 49.25, 54, 64.75, 110.

The minimum and maximum are observations; the quartiles may fall between observations. And because quartiles mark quarter positions, small samples and repeated values can prevent four groups of exactly equal size.

Five numbers describe where the data sit and how they spread.

2.5Spread: the IQR and the range

The interquartile range is IQR = Q3 − Q1 = 64.75 − 49.25 = 15.5 thousand dollars: the width of the interval holding (approximately) the middle half of the data.

The range is max − min = 110 − 30 = 80, set entirely by the two most extreme values.

In this list, the quartiles and IQR would not change if the largest salary were larger still, as long as it remained the largest. The range would. Spread describes how far apart the values are; centre describes where they are. They answer different questions, so a summary needs both.

Check yourself: spread is not centre

Q1 = 49.25 and Q3 = 64.75. (a) How many salaries lie between Q1 and Q3, and what does IQR = 15.5 describe? (b) A classmate says: “The IQR is 15.5, so a typical salary is about $15,500.” What has gone wrong?

Show answers

(a) Six of the twelve: 50, 52, 52, 56, 60, 63, the middle half. IQR = 15.5 is the width of the interval holding them, a measure of spread. (In small samples or with repeated values, the count between Q1 and Q3 need not be exactly half.)

(b) The classmate treated a spread measure as a centre. A typical salary is described by the median, 54, or the mean, 58. 15.5 is a distance between two positions, not a salary anyone earns.

2.6The 1.5 × IQR rule for potential outliers

Compute two fences:

lower fence = Q1 − 1.5 × IQR     upper fence = Q3 + 1.5 × IQR

A value is flagged as a potential outlier only if it lies strictly beyond a fence.

For the salaries: 1.5 × 15.5 = 23.25, so the lower fence is 49.25 − 23.25 = 26.0 and the upper fence is 64.75 + 23.25 = 88.0. Only 110 lies beyond a fence.

A box plot draws the five-number idea. The box runs from Q1 to Q3 with a line at the median; the whiskers reach the most extreme values still inside the fences (30 and 70); anything beyond a fence is drawn as its own point. The dashed lines are the fences: computed boundaries, not observations.
Python
q1, q3 = s.quantile(0.25), s.quantile(0.75)
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
flag = (s < lower) | (s > upper)      # True where a value lies strictly beyond a fence

print(iqr, lower, upper)
print(s[flag])                         # the flagged rows; the Series itself is unchanged
15.5 26.0 88.0
11    110
Name: salary, dtype: int64

Three cautions. The rule is a rule of thumb: it is neither a definition of every outlier nor a statistical test. Fences are computed boundaries, not the observed min and max. And a flagged value is unusual for its attribute, which may mean an error or a correct but rare value; the data alone usually cannot tell which.

A flag is a question for whoever produced the data, not an instruction to delete.

Beyond the lecture: why 1.5?

John Tukey proposed it in 1977 as a practical compromise. One way to see what it does: if data come from a bell-shaped (normal) distribution with mean μ and standard deviation σ, then Q1 ≈ μ − 0.674σ and Q3 ≈ μ + 0.674σ, so IQR ≈ 1.349σ and the fences sit at about μ ± 2.7σ. Only about 0.7% of normal data falls beyond them. So in well-behaved data the rule flags very little; in skewed data (like most salary lists) it flags more on the long side, which is a reason to treat flags as prompts, not verdicts. Because it is built from quartiles, the rule is itself robust: the extreme value cannot drag the fences out to hide itself, as it would with a rule built from the mean and standard deviation.

Check yourself: fences and flags

Using Q1 = 49.25 and Q3 = 64.75: (1) calculate the fences; (2) which salaries are flagged? (3) The lowest salary is 30. Is it flagged, and are the fences the same as the minimum and maximum? (4) Does the flag show that 110 is an error? Write one thing you would record and one thing you would not do yet.

Show answers
  1. IQR = 15.5; 1.5 × IQR = 23.25; lower fence 26.0, upper fence 88.0.
  2. Only 110 (110 > 88.0).
  3. 30 is not flagged, because 30 > 26.0. Neither 26 nor 88 is a salary in the list: fences are computed boundaries; the minimum 30 and maximum 110 are observations.
  4. No. The rule only shows 110 is unusual relative to the other eleven. It could be a correctly recorded high salary (a few highly paid managers raise a company's mean) or an entry or unit error. Record: “salary 110 flagged by the 1.5 × IQR rule; asked the data owner whether it is correct.” Do not yet delete the row, replace the value, or cap it.
Detect, record and ask — for salaries as for the patient file.

2.7Salary explorer

Everything in this part, live. Drag the largest salary and watch which summaries react. Then try making it small enough that it stops being flagged, and notice that the quartiles never moved.

How each summary responds to one extreme value

The other eleven salaries stay fixed. Quartiles use pandas' default (linear) method; σ uses N, s uses N − 1.

Monday's practical follows exactly this pattern: profile a new table, read the rows of describe(), compute the fences in pandas and flag rows without changing the DataFrame.

Reading: Tan §2.2; Han §2.2, §2.4; Badia §1.1, §3.2, §3.3.

Part 3, from Lecture 13

Missing values and cleaning decisions

Part 2 detected and recorded problems without repairing anything. This part decides what to do about entries that are unknown, and how to record why. By the end you should be able to distinguish four kinds of recorded entry and say when converting one to a missing marker is justified; explain what retaining, deleting, filling with a constant, and filling with the mean or median each assume and change; and record a cleaning decision so that observed values, estimates and open questions stay separate.

The whole part follows four steps, which are also its summary:

1. Name what is unknown2. Ask how it became unknown3. State what your action assumes4. Record what remains uncertain

3.1Field 4, revisited

Two facts about field 4 are known: the documentation says valid values are 1 to 10 and 0 is the missing code; and a data-entry error changed every 10 into 0. Part 2 ended with “detect, record and ask” because the repair needs information the file does not contain. Which information? The original forms, or a log of the entry error, showing which zeros were tens. Until that arrives, each zero may be a missing measurement and may be a 10, and the table cannot tell which.

3.2Four kinds of recorded entry

Before deciding anything, we need names for what we are looking at.

KindMeaningExample
Observed valuea recorded value that the evidence gives no reason to change. Being in range is not proof that it is accurate; it only means we have no reason to doubt it.field 4 = 2, inside the documented range 1–10
Documented missing markera code that the documentation says means “not recorded”: −9999, a blank, an empty string, “n/a”. If the documentation does not mention it, software will average −9999 as if it were a measurement.weight = −1, documented as “not recorded”
Not applicableno value exists for this object. Typical cause: a conditional part of a form that is only filled in after a certain earlier answer.driver's-licence number for someone with no licence
Ambiguous or corruptedthe entry could mean more than one thingfield 4 = 0: missing, or a 10 changed by the entry error

3.3Converting a marker is not estimating a value

Two operations are easily confused, and the difference is the most important idea in this part.

Representation correction

A documented marker is replaced by the software's missing marker (NaN in pandas). The measurement stays unknown; only how we write down that we do not know changes.

Estimation

A number is supplied for a measurement that is unknown. That number is an estimate, not an observation. It changes what we claim to know.

When is converting justified? A marker can be converted only if it is (1) documented, and (2) unambiguously distinguishable from legitimate observations.

The rule is not about any particular value. 0 can be a perfectly good missing code wherever 0 cannot be a real value and the documentation says so.

Field 4 shows how condition (2) can fail. The code 0 was distinguishable from the values 1 to 10 until the entry error turned real tens into 0. The documentation did not change, but the zeros are no longer distinguishable, so converting them is no longer justified: it would overwrite real tens.

Why does representation correction matter at all, if nothing is learned? Because software treats a code as a number until told otherwise:

Python
import numpy as np
pt = pd.DataFrame({"patient": ["A", "B", "C", "D", "E"],
                   "weight":  [61.2, -1, 70.5, -1, 82.0]})   # documentation: -1 = not recorded
print(pt["weight"].mean())                          # the codes are averaged as weights

pt["weight"] = pt["weight"].replace(-1, np.nan)     # representation correction
print(pt["weight"].mean(), pt["weight"].isna().sum())
42.339999999999996
71.23333333333333 2

Before the correction the “mean weight” of 42.3 kg was nonsense; afterwards pandas skips the two unknowns and averages the three real weights (and isna() can finally count them). You can also do this at load time with pd.read_csv(..., na_values={"weight": [-1]}), scoped to the one column where the code is documented. (Note the trailing digits in 42.339999999999996: that is ordinary floating-point rounding, not an error.)

For field 4, the defensible move is the opposite: change nothing in the source, and label the ambiguity in a working copy:

Python
work = df.copy()                                   # the source stays as received
work["field4_status"] = np.where(work["field4"] == 0,
                                 "unresolved: missing or 10", "recorded")
print(work[["field1", "field4", "field4_status"]])
  field1  field4              field4_status
0    012       0  unresolved: missing or 10
1    020       2                   recorded
2    027       0  unresolved: missing or 10
Marking an entry as missing states what we do not know. Filling it supplies an estimate.

Check yourself: kinds of entry

Name each entry's kind, and say whether the evidence justifies converting it to the software's missing marker.

  1. On a credit-card application the driver's-licence number is blank; the applicant has no licence.
  2. In a patients table, Weight is −1 for some patients; the documentation says −1 marks a weight that was not recorded.
  3. In the patient file, field 4 is 0 (valid 1–10; 0 is the missing code; every 10 was entered as 0).
  4. In the same file, field 4 is 2.
Show answers
  1. Not applicable. No licence number exists, so none may be estimated. Keep the reason: “not applicable” differs from “exists but not recorded”. Either a separate value or a missing marker plus a reason column preserves it; the storage form is a design choice.
  2. Documented missing marker. −1 cannot be a weight, so it is unambiguous: converting is justified. The weight remains unknown.
  3. Ambiguous. Missing, or a corrupted 10. Converting is not justified: it would overwrite real tens. Keep it unresolved.
  4. An apparently valid observation. In range, and nothing supplied warrants a change. In range is not proof of accuracy, but the evidence justifies no change.

Common mistakes: “a blank means fill it” (a); “converting to NaN loses data” (b); “0 is a number, so it is a value” (c); “in range means correct” (d).

3.4How values become unknown: one sensor, three situations

Now suppose the missing entries are genuinely missing. Why they are missing changes what we may do. An air-temperature sensor takes readings at scheduled times, and its record has gaps. The target is fixed:

Target: the mean air temperature over all scheduled observation times, each time counted equally.

For each situation, ask: is the mean of the recorded temperatures expected to be too high, too low, neither in particular, or does it depend?

1. The battery runs out Battery runs out Reading recorded? Temperature unrelated to whether a readingis recorded (assumed) 2. No battery replacement when it rains Rain Battery not replaced Reading recorded? Temperature may be related 3. The sensor fails below zero Temperature below 0° Sensor fails Reading recorded? the only causeof gaps (assumed)
What decides whether a reading exists, in each situation. The question is always whether that cause is connected to the temperature itself.

Situation 1: the battery runs out

Readings stop until the battery is replaced. Assumption: whether a scheduled reading is recorded is unrelated to the temperature at that time. Answer: neither in particular. The recorded mean is a fair guide on average: not guaranteed to equal the full-period mean in this particular period, and based on fewer readings, but not expected to err in any one direction. (One long gap in a single season would break the assumption — a month-long outage in winter loses mostly cold readings — which is exactly why the assumption is written down.)

Situation 2: no replacement when it rains

The person who replaces batteries does not do it when it rains, so batteries are more likely to be dead on rainy days. Assumption: whether a reading exists depends on rain, not on temperature itself. Rain makes a gap more likely, not certain. Answer: it depends. Recorded readings over-represent dry times. That matters only if rainy and dry times differ in temperature — a relation the table may or may not show.

Situation 3: the sensor fails below zero

Assumption: these failures are the only cause of gaps. Answer: too high. Every recorded value is at or above zero and every missing one is below zero. The missing values all come from one part of the range, so the recorded values are not an impartial guide to them, and no recorded value says how far below zero the missing ones were.

The same gaps can have different causes. All three situations can leave exactly the same pattern of gaps in the table. What decides the right action is knowledge of how the data were collected, and the table alone may not reveal it.

Before choosing an action, ask what decided whether a value was recorded.

Beyond the lecture: the standard names for these three situations

The lecture avoids jargon, but you will meet these terms (introduced by Donald Rubin in 1976) in every textbook and library:

  • MCAR, missing completely at random (situation 1): whether a value is missing is unrelated to anything, recorded or not. The recorded values are a fair random subset.
  • MAR, missing at random (situation 2): missingness depends only on other recorded information (rain), not on the missing value itself. If rain is recorded, you can correct for it, e.g. by averaging rainy and dry times separately and weighting each by how often it rains. If rain is not recorded, you cannot — which is why the lecture answers “it depends”.
  • MNAR, missing not at random (situation 3): missingness depends on the unrecorded value itself. No method using only the recorded data can remove the bias; you need outside information (here, a malfunction log or another sensor).

The name “missing at random” is famously confusing, since MAR data are not missing randomly in the everyday sense. Remember it as “random once you account for what you recorded”.

Simulate a year of sensor readings

365 daily temperatures with a seasonal cycle. Choose why readings go missing and compare the mean of the recorded readings with the true mean of all 365. Filled dots are recorded readings; small ticks along the bottom mark missing days.

3.5Four treatments of missing values

A company's customer table has no recorded income for some customers. Four common ways to treat those gaps:

Schematic, not a dataset. Each mini-table has an income column and one other column. Grey = observed, white with a cross = missing, black = estimated, hatched row = removed.
TreatmentWhat it changesWhat it assumes or risks
Retain as missingNothing is added; the gaps stay marked.Nothing is invented. Each summary uses the recorded entries only, so report how many it used. Some methods need complete rows, and retaining does not by itself answer a question about all customers.
Delete the rowThe rows go, along with their other recorded values.A partly recorded row still carries information, and it is lost. Conclusions extend to all customers only if the deleted ones resemble the rest. Reasonable when few rows are missing, but still an assumption; the below-zero sensor is a case where it fails.
Fill with a constantOne label, such as “Unknown”, is shared by every gap.A program may treat “Unknown” as a meaningful group, and the column stops being purely numeric. A numeric constant such as −99 enters arithmetic as if it were a measurement and distorts any summary that uses magnitudes (mean, minimum).
Fill with mean or medianAn estimate is placed in every gap.Assumes the missing incomes look like the recorded ones. Each filled entry is an estimate. (Section 3.6.)

Other methods predict each missing value from the customer's other attributes (for example from age and job). They are often better estimates, but they are still estimates.

In pandas (incomes in thousands of dollars, three missing):

Python
inc = pd.Series([42, 48, np.nan, 55, 56, np.nan, 58, 61, np.nan, 70], name="income")

def summary(x):
    return f"n={x.count()}  mean={x.mean():.2f}  median={x.median():.2f}  sd={x.std(ddof=0):.2f}"

print("recorded   ", summary(inc))                        # retain: pandas skips NaN
print("mean fill  ", summary(inc.fillna(inc.mean())))
print("median fill", summary(inc.fillna(inc.median())))
print(inc.fillna("Unknown").dtype)                          # constant label

# deleting rows: use the whole table so you see what else goes
# customers.dropna(subset=["income"])  drops every column of those 3 customers
recorded    n=7  mean=55.71  median=56.00  sd=8.33
mean fill   n=10  mean=55.71  median=55.71  sd=6.97
median fill n=10  mean=55.80  median=56.00  sd=6.97
object

Look at the last column of numbers: both fills shrank the spread, from 8.33 to 6.97. Ten values now look less variable than seven did, because three of them were placed exactly at the centre. And the “Unknown” fill silently turned a numeric column into a text (object) column.

Every treatment changes something and assumes something. Name both.

3.6Filling with the mean or the median

Suppose each missing income is filled with the mean, or the median, of the recorded incomes. Where do the filled entries land? All at one point: the chosen centre. Consequences:

  • Every filled entry is the same number, so the filled column shows an artificial concentration at that value.
  • One repeated number cannot show how uncertain each missing income is. Each filled entry is an estimate, not an observation. As the code showed, the spread is understated.
  • The smallest and largest entries do not change.

The two fills keep different summaries:

  • Mean filling: the column's mean stays equal to the recorded mean. (Adding values exactly at the mean cannot move the balance point.)
  • Median filling: the column's median stays equal to the recorded median; the mean generally moves (55.71 → 55.80 above).

Choosing between mean and median is the question of which centre to use, from Part 2. Neither choice says anything about why the incomes are missing. If high earners are the ones who decline to report, both fills are biased low. Try it:

What filling does to a distribution

400 simulated incomes (thousands of dollars, slightly right-skewed). Grey bars are recorded incomes, black bars are filled-in entries. The dashed line is the true mean of all 400, which in real life you would not know.

Who goes missing:
Treatment:

A filled-in value is an estimate, and it may not be correct.

Check yourself: consequences of three actions

A customer table has no recorded income for many customers. Recorded incomes are roughly symmetric with mean $56,000. An analyst considers (A) deleting every customer without an income; (B) filling each gap with the label “Unknown”; (C) filling each gap with $56,000.

  1. For each option, name one thing that is lost or assumed.
  2. After C, a colleague reports: “The most common income is $56,000, and incomes cluster around the middle.” Which comparison would show whether these statements come from the filling, and under what condition would the first one be true?
Show answers

(a) A: the other attributes of those customers are lost; conclusions extend to all customers only if the deleted ones resemble the rest. B: a program may treat “Unknown” as a meaningful group, and the column is no longer purely numeric. C: the missing incomes are assumed to look like the recorded ones; each filled entry is an estimate.

(b) Compare the filled column with the recorded incomes alone. $56,000 becomes the most common entry if the number of filled entries exceeds the count of the most frequent recorded income: likely when many are missing, but not guaranteed. The cluster at $56,000 exists in the filled column but not in the recorded incomes, so the filled table cannot show it is a feature of the customers. And the filled column's mean equals the recorded mean: that is a property of mean filling, not evidence about the missing customers.

Two opposite mistakes: “mean filling is neutral because the mean is unchanged”, and “every pattern in a filled column is fake”. The recorded incomes still carry real information.

3.7Recording a decision: the cleaning decision log

Whatever you choose, someone else must be able to check it, and undo it if needed. One log entry has six fields:

Findingwhat the profile or a check showed
Evidencedocumentation, later information, counts
Actionwhat was done, or deliberately not done, and where; the source stays unchanged
Assumptionwhat the action takes to be true
Affected datawhich rows and fields, and how many
Unresolvedwhat remains unknown

Two words are used carefully from here on:

An action is recorded when its log entry makes it auditable. It is defensible only if its assumption fits what is known about how the data were collected.

A perfectly written log entry can describe an indefensible action. Writing an assumption down does not make it true.

Field 4 under alternative interpretations

The three printed rows hold 0, 2, 0 in field 4. If both zeros were really tens, what is the mean of the three measurements? Because we do not know, report the mean of the available measurements under each interpretation:

Interpretation of the two zerosMeasurementsnMean
Both are missing codes212
One is a 10, the other a code (either way round)2, 1026
Both are tens10, 2, 10322/3 ≈ 7.33
valid scale 1 to 10 2 (n = 1) 6 (n = 2) 7.33 (n = 3) 0.67: invalid
Alternative interpretations, not repaired values. The crossed circle is the average of 0, 2, 0 with the codes treated as numbers: it summarises no measurement and lies off the valid scale.

Note that n changes with the interpretation. These are not three “possible true means”: wherever a zero is a missing code, that measurement remains unknown.

A worked entry: field 4 of the patient file

FindingIn field 4, two of the three printed rows hold 0; isna() reports no missing entries.
EvidenceDocumentation: valid values 1 to 10; 0 is the missing code. Later information: every 10 was entered as 0.
ActionNo value is changed; the source file stays as received. In a working copy the zeros are labelled “unresolved: missing or 10”. Field 4 is left out of numeric summaries, or each summary is reported under every interpretation with its n. The data producers are asked for the original forms or the entry log.
AssumptionNone about any individual zero. Entries 1 to 9 are taken as recorded; this is stated and unverified.
Affected dataEvery row with field 4 = 0: two of the three printed rows; the count in the full file is to be reported. No other field is touched.
UnresolvedHow many zeros are tens. The mean of the available measurements is 2, 6 or 22/3, depending on the interpretation.
Why defensibleIts only assumption fits what is known; any other action would need to know which zeros are tens.

The shaded row is not a seventh field. It is the judgement that separates a recorded action from a defensible one. Here the defensible action is a non-action plus a question.

Check yourself: write a decision-log entry

The sensor malfunctions whenever the temperature is below zero, and these failures are the only cause of gaps. The analysis needs the mean temperature over the whole period, each scheduled time counted equally. Choose one action — retain the gaps; delete those rows; fill with the mean recorded temperature; or request more information — and write the entry, stating the assumption and what remains uncertain.

Show discussion

An entry is judged on whether its assumption and uncertainty are stated honestly and fit the collection, not on which action it picked.

  • Every recorded temperature is at or above zero and every missing one below, so the target mean is lower than the recorded mean.
  • Filling with the recorded mean, or deleting the rows and averaging the rest, reports a value that is too high. Knowing the missing values are low still gives no good value for each one.
  • Retaining the gaps preserves the uncertainty but does not supply the full-period mean.
  • A defensible entry reports what can be reported: the number of gaps; the mean over the times not below zero, labelled as such; and the statement that the full-period mean is lower. It requests another source or the malfunction log.
  • A mean fill logged with the honest assumption “the missing times were like the recorded ones” is well recorded, but the assumption contradicts the known failure process, so the action is not defensible for this target.

Common mistakes: “fill with the minimum”; “few gaps, so delete”; “I stated my assumption, so my choice is justified”; “retaining the gaps answers the question”.

Writing an assumption down makes it auditable; only an assumption that fits the collection makes the action defensible.

Exit question

A colleague replaces every 0 in field 4 by NaN and then fills the NaN entries with the column median. Name the two operations and what each assumes. Which is not justified here, and why?

Show answer

The first is a representation correction, justified only when the marker is distinguishable from legitimate observations. The second is an estimation, which assumes the missing entries resemble the recorded ones. The first is not justified, because some zeros may be tens; the second then builds estimates on top of that error (and would fill a corrupted 10 with something near 2).

Reading: Han §2.4; Badia §3.3; Tan §2.2.

Part 4, from Lecture 14

Scaling numeric attributes: min–max normalization and z-score standardization

After deciding what to do with unknown entries, perfectly usable numeric attributes may still be recorded in very different units and ranges. By the end of this part you should be able to explain the standard deviation as the root-mean-square distance from the mean, compute it with a stated divisor, and recognise when a reported value used N − 1; compute and interpret a min–max value and a z-score; and record what a scaling step used, and say what rescaling does not change.

4.1Why measurement scale matters

Some calculations combine attributes by their numerical magnitudes. The commonest is the distance between two objects. With two attributes, the straight-line (Euclidean) distance between person p and person q is

d(p, q) = (agep − ageq)2 + (incomep − incomeq)2

A difference of a few thousand dollars is numerically far larger than a difference of a few years, so income will dominate this sum purely because of the unit it is recorded in. Change metres to centimetres and the same quantity becomes 100 times “bigger”, without anything real changing. Methods later in the course, such as nearest-neighbour and clustering methods, use exactly this kind of calculation.

Who is most similar to person P?

Six people, two attributes. The table shows each person's distance from P. Switch the scaling and see whether the nearest neighbour changes.

Two qualifications matter. Each attribute can still be described and summarised in its own unit; there is nothing wrong with the raw values. And rescaling does not decide how important an attribute should be; that is a choice for the analysis. Rescaling only prevents accidental dominance caused by units.

Large numerical scale does not mean greater importance. An attribute should not dominate a scale-sensitive calculation simply because of the units in which it is recorded.

4.2The standard deviation: spread about the mean

Before standardizing with a z-score, we need a way to describe how spread out values are around the mean. Part 2's IQR measured the spread of the middle half around the median; now we want a spread that goes with the mean.

Deviations from the mean

The salaries have mean x̄ = 58. Each value's signed distance from the mean, xi − x̄, is its deviation. Negative deviations lie below the mean, positive ones above.

salary xi3036475052525660637070110total
deviation xi − 58−28−22−11−8−6−6−2+2+5+12+12+520
squared deviation78448412164363644251441442,7044,550

The deviations add up to zero. This is true of any list, because the mean is the balance point: positive and negative deviations cancel exactly. (Proof in one line: Σ(xi − x̄) = Σxi − N·x̄ = N·x̄ − N·x̄ = 0.) So the raw sum of deviations cannot measure spread.

Squaring prevents the cancellation

Square each deviation. Every square is at least 0, so deviations on both sides now add up instead of cancelling.

The variance is the mean of the squared deviations. The standard deviation σ is the square root of the variance; taking the root returns the result to the attribute's own unit.

σ = 1N Σi=1..N (xi − x̄)2

In words: the root-mean-square distance from the mean. Square the distances, take their mean, take the square root. Read it as a typical size of deviation.

For the salaries, dividing by N = 12: variance = 4,550 / 12 ≈ 379.17 (thousand dollars)2, and σ = √379.17 ≈ 19.47 thousand dollars.

Each bar is one salary's squared deviation. The single value 110 contributes 2,704 of the 4,550 total, about 59%: squaring gives large deviations extra weight.

Properties

  • σ describes spread about the mean; it is the natural spread measure when the mean is the chosen centre (the IQR pairs with the median).
  • σ = 0 only when all values are equal; otherwise σ > 0.
  • Squaring gives large deviations extra weight: a deviation twice as large contributes four times as much to the variance.
  • σ is in the attribute's unit (thousand dollars); the variance is in the squared unit, (thousand dollars)2, which is why we usually report σ.
  • σ is not a limit on individual deviations: 110 lies 52 above the mean and 30 lies 28 below it, both more than 19.47 away.

Beyond the lecture: why square rather than take absolute values?

Taking absolute values also prevents cancellation, and gives the mean absolute deviation (for the salaries, 166 / 12 ≈ 13.8). It is a fine descriptive measure. Squares won historically because they behave well algebraically: variances of independent quantities add, the mean is exactly the point that minimises the sum of squared deviations, and the normal distribution is built on σ. The price is sensitivity to extreme values, which you can see in the chart above.

The standard deviation is the root-mean-square distance from the mean, in the attribute's own unit: a typical size of deviation.

4.3Two conventions: dividing by N or by N − 1

Dividing the sum of squared deviations by N describes the spread of the values at hand. A second convention divides by N − 1. It is used when the values are a sample and the aim is to estimate the spread of a larger population.

  • This course uses N for descriptive standard deviations and for scaling. In pandas this is written ddof=0 (“delta degrees of freedom”: the divisor is N − ddof).
  • pandas' s.std() and the std row of describe() divide by N − 1 (ddof=1) by default.
  • Neither is an error. A report states which divisor it used.
Python
s = df["salary"]          # the twelve salaries, thousand dollars
s.std(ddof=0)             # divide by N
s.std()                   # divide by N - 1 (pandas default)
np.float64(19.47220240924654)
np.float64(20.338052110179177)

Both are in thousand dollars; 4,550 / 11 = 413.64 and √413.64 ≈ 20.34. The wrapper np.float64(...) only says that pandas returned a NumPy number.

Beyond the lecture: why N − 1 exists, and a trap between libraries

Deviations are measured from the sample mean, and the sample mean is, by construction, the point closest to the sample (it minimises the sum of squared deviations). So squared deviations from it are on average a little smaller than squared deviations from the true population mean would be. Dividing by N − 1 instead of N inflates the result just enough to correct this on average (Bessel's correction). The difference shrinks as N grows: with N = 12 it is 4.4%; with N = 1,000 it is 0.05%.

The trap: libraries disagree on the default. pandas Series.std() uses N − 1; NumPy np.std() uses N; scikit-learn's StandardScaler (which you will meet later) uses N. Always pass ddof explicitly, and write it in the record.

State the divisor. In this course: N (ddof=0).

4.4Min–max normalization

Min–max normalization maps a value to its position within the recorded range:

v′ = v − minmax − min

Read it in two steps. Subtracting min measures how far v lies above the recorded minimum. Dividing by max − min expresses that distance as a fraction of the recorded range. Therefore:

  • the recorded minimum maps to 0 and the recorded maximum to 1;
  • a value halfway between them maps to 0.5;
  • the result has no unit, because the unit cancels in the ratio.

So v′ = 0.25 means the observation lies one quarter of the way from the recorded minimum to the recorded maximum.

Terminology. Books do not use normalize and standardize consistently. In this course, normalization means min–max and standardization means z-score.

Scenario 1 (hypothetical)

An attribute income has a stated minimum of $12,000 and maximum of $98,000. Where does $73,600 map?

v′ = 73,600 − 12,00098,000 − 12,000 = 61,60086,000 ≈ 0.716

$73,600 lies about 71.6% of the way from the recorded minimum to the recorded maximum. The number 0.716 is a position within the range: not a probability, and not “71.6% of the income”. The scenario states only a minimum and a maximum; it gives no list of incomes.

The twelve salaries

With min = 30 and max = 110 (range 80), v′ = (v − 30) / 80. Salary 52 maps to 22/80 = 0.275.

salary3036475052525660637070110
min–max00.0750.21250.250.2750.2750.3250.3750.41250.50.51
Every dot sits directly below its original position: min–max changes the numbers on the axis, not the arrangement of the data. Order and relative spacing are kept.

Notice two things. First, 70 maps to 0.5: it is the midpoint of the recorded range, not the median (the median, 54, maps to 0.3). Second, eleven of the twelve values lie in [0, 0.5]: the single value 110 sets the maximum, and the other eleven span only 40 of the range of 80.

Beyond the lecture: other target ranges

To map onto any interval [a, b] instead of [0, 1], stretch and shift: v′ = a + (v − min)(b − a) / (max − min). For [−1, 1], a = −1 and b = 1. The logic is identical; only the labels at the ends change.

A min–max value tells you where a value lies within the recorded range.

4.5Z-score standardization

Z-score standardization describes a value by its distance from the mean, measured in standard deviations:

z = v − x̄σ

where x̄ is the attribute's mean and σ its standard deviation, computed here with the N divisor.

The numerator is the signed distance from the mean; dividing by σ expresses it in units of typical spread. So z > 0 means above the mean, z < 0 below, z = 0 is the mean; |z| counts standard deviations (z = 2 means two standard deviations above); and z has no unit.

Scenario 2 (hypothetical, separate from Scenario 1)

Stated mean $54,000, stated standard deviation $16,000. Then $38,000, $54,000 and $70,000 have z = −1, 0, +1. Since $73,600 is above $70,000, expect its z-score to exceed 1:

z = 73,600 − 54,00016,000 = 19,60016,000 = 1.225

$73,600 lies 1.225 standard deviations above the stated mean: a standardized distance, not a percentage and not an amount of money.

The twelve salaries

With mean 58 and σ = 19.47: z = (v − 58) / 19.47.

salary3036475052525660637070110
z-score−1.438−1.130−0.565−0.411−0.308−0.308−0.1030.1030.2570.6160.6162.670
Same dots, new labels. The mean, 58, maps to z = 0 even though 58 is not one of the observed salaries. Tick marks on the lower axis are whole standard deviations.

The raw value 70 tells you a salary; its z-score, 0.62, adds context: 70 lies about 0.62 standard deviations above this list's mean. Likewise 110 lies 2.67 SDs above and 30 lies 1.44 below.

After standardizing, the twelve z-scores have mean 0 and standard deviation 1 (with the same N divisor). Why: subtracting x̄ moves the balance point to 0; dividing every deviation by σ divides the root-mean-square deviation by σ, giving 1. pandas' default std() of the z-scores gives 1.044 only because it uses N − 1 (√(12/11) ≈ 1.044).

A raw value gives its magnitude; a z-score locates it relative to the mean and spread of the data.

4.6Two separate scenarios

The worked income examples came from two separate hypothetical scenarios. Scenario 1 supplied a minimum and maximum, enough for min–max. Scenario 2 supplied a mean and standard deviation, enough for a z-score. Neither supplied the incomes behind its parameters. So 0.716 and 1.225 are not two descriptions of one income distribution; each belongs only to its own scenario. (For the salaries, by contrast, both sets of parameters come from the same twelve values, so the two tables above do describe the same data.)

4.7Recording a scaling step

To reproduce a scaling step, another analyst must know what was scaled and with which parameters. For the salary column:

Column and unitsalary, thousand dollars
Methodz-score (or min–max)
Parametersmean 58 and σ = 19.47 thousand dollars, N divisor (ddof=0); or min 30 and max 110 thousand dollars
Rows usedn = 12; missing entries excluded and counted
Originalkept; scaled values added as a new column

The parameters are computed once from the data they describe, recorded, and then reused for later values. They are not recomputed for each new value. pandas skips missing entries when computing min, max, mean or standard deviation, and a missing entry stays missing after scaling; that is why the record states which rows were used. As with Part 3's decision log, the purpose is reproducibility.

Beyond the lecture: why “compute once, reuse” matters so much later

When you build a predictive model (the Predict stage), you fit it on training data and evaluate it on held-out test data. The scaling parameters must come from the training data only and then be applied, unchanged, to the test data and to every future value. Recomputing them on the test data would let information from the test set leak into the preparation, and make the evaluation look better than reality. Libraries formalise this as fit (compute and store the parameters) and transform (apply stored parameters).

Going back: the inverse maps

Recorded parameters also make the transformation reversible. Solve each formula for the original value:

original = x̄ + z·σ      original = min + v′·(max − min)

For Scenario 2: 54,000 + 1.225 × 16,000 = 73,600. Without the recorded parameters, this recovery is impossible.

Compute the parameters once, record them, and reuse the same parameters for later values.

4.8What rescaling does not do

Rescaling changes the axis used to describe the data; it does not repair or reshape the data.

  • Order and relative spacing are preserved. Both transformations subtract one number and divide by another, using the same two numbers for every observation (a straight-line map). So the shape of the distribution is unchanged.
  • Extreme values stay extreme. 110 stays far from the other salaries under either transformation.
  • Scaling does not make data normal. It relabels the axis; it does not change the pattern. A skewed column stays exactly as skewed.
  • Extreme values affect the parameters. 110 contributes about 59% of the squared deviations, inflating σ, and sets the min–max maximum, compressing the other eleven salaries into the lower half.
  • Reused min–max parameters can give values outside [0, 1]. If min 30 and max 70 had been recorded earlier (from the first eleven salaries) and were later applied to 110: (110 − 30) / (70 − 30) = 2.0. Valid arithmetic: the new value lies outside the range the parameters were recorded on. Record it and examine it; do not silently clip it to 1.

A constant column

If every value in a column is the same, then σ = 0 and max − min = 0, so both formulas divide by zero. Each numerator is also 0, so every row is 0/0.

Python
c = pd.Series([4.0, 4.0, 4.0, 4.0], name="constant")
print(((c - c.mean()) / c.std(ddof=0)).tolist())
[nan, nan, nan, nan]

pandas does not stop with an error. It quietly returns NaN in every row, which looks exactly like a column of missing values. Before scaling, check that the denominator is non-zero. If the column is constant, record it as “not scaled”. (A constant column carries no information for comparing objects anyway.)

Rescaling changes the axis, not the underlying pattern of the data. Before scaling, check the denominator is non-zero.

4.9Scaling playground

Rescale any list

Type numbers separated by spaces or commas. The parameters are computed once from this list (σ with N), then you can apply the same stored parameters to a new value.

Things to try: switch to “Salaries in dollars” and confirm that every min–max value and z-score is unchanged (both are unit-free). Switch to “Salaries without 110”, then enter 110 as the new value: min–max gives 2.0. Choose “Constant column” to see the zero-denominator guard.

4.10Checks

Check 1: spread about the mean, and the divisor

For the twelve salaries, the mean is 58 and σ (dividing by N) is 19.47.

  1. Which single salary contributes most to σ, and why?
  2. A classmate runs df['salary'].std(), sees 20.34 and says the lecture's 19.47 is wrong. Reply.
  3. True or false: every salary lies within 19.47 of the mean.
Show answers

(a) 110: its deviation, +52, is the largest; squared it is 2,704 of 4,550, about 59%. (b) Both are correct with different divisors: pandas' default divides by N − 1 (ddof=1) giving 20.34; the course divides by N (ddof=0) giving 19.47, obtained with std(ddof=0). A report states which. (c) False: 110 is 52 above and 30 is 28 below. σ is a typical size of deviation, not a limit.

Common mistakes: “the largest salary always contributes most” (here it does because its deviation is largest; a very low value could contribute more); “one of the two SDs is a mistake”; “the SD is a maximum distance”; “the SD has no unit”.

Check 2: min–max values and their limits

Normalize the salaries to [0, 1] with min 30 and max 110.

  1. Where does 70 map?
  2. Eleven of twelve normalized values lie between 0 and 0.5. Why?
  3. If min and max had been recorded from the first eleven salaries (30 and 70) and then applied to 110, what results? Is it an error?
Show answers

(a) (70 − 30) / 80 = 0.5. (b) 110 alone sets the maximum: the range is 80 but the other eleven span only 40 of it. (c) (110 − 30) / (70 − 30) = 2.0. Valid arithmetic: 110 lies outside the range the parameters came from. Record and examine it; do not clip it or report it as a computing error.

Common mistakes: “min–max values are always between 0 and 1”; “0.5 means the median” (54 maps to 0.3); “normalizing removes the extreme value”; “a result above 1 means the code is wrong”.

Check 3: interpreting z-scores

  1. z(110) = 2.67 and z(30) = −1.44. Interpret each in one sentence.
  2. If salaries were recorded in dollars instead of thousands, what happens to the mean, σ and the z-score of 110?
  3. A classmate says: “After standardizing, the values lie between −1 and 1 and follow a normal distribution.” Correct both claims.
Show answers

(a) 110 lies 2.67 standard deviations above the mean; 30 lies 1.44 standard deviations below it. (b) The mean becomes 58,000 dollars and σ becomes 19,472 dollars (both × 1,000); z(110) stays 2.67 because numerator and denominator change by the same factor. Min–max values are also unchanged. (c) Z-scores are not bounded: 110 has z = 2.67. Standardizing shifts and rescales every value by the same two numbers, so order, spacing and shape are unchanged; 110 is still far from the rest. It does not make the data normal.

Common mistakes: “z = 2.67 means 2.67 thousand dollars above”; “z-scores are percentages”; “changing units changes the z-score”; “standardized means normal”; “standardizing removed the extreme value”.

Exit question

Your notebook standardizes a salary column. (1) Write the record another analyst needs to reproduce the step, or to recover an original salary from its z-score. (2) Name one situation in which the same code returns NaN in every row.

Show answer

(1) Column and unit; method (z-score); mean and σ with units; divisor (ddof=0); rows used, with the number of missing entries excluded; original column kept. Recovery: original = mean + z × σ. (2) A column whose values are all equal: σ = 0, so each division is 0/0 and pandas returns NaN without stopping.

4.11Reference: the pandas pattern

For reference; you will practise it with worked examples before being expected to write it yourself.

Python
work = df.copy()                                    # keep the original table
col = work["salary"]
params = {"min": col.min(), "max": col.max(),
          "mean": col.mean(), "sd": col.std(ddof=0),  # N divisor
          "n_used": int(col.count()), "n_missing": int(col.isna().sum())}

rng = params["max"] - params["min"]
if rng == 0 or params["sd"] == 0:                   # check the denominator first
    print("constant column: not scaled")
else:
    work["salary_minmax"] = (col - params["min"]) / rng
    work["salary_z"] = (col - params["mean"]) / params["sd"]

# later values reuse the SAME stored parameters
new = 120
print((new - params["mean"]) / params["sd"], (new - params["min"]) / rng)
3.184026064281192 1.125

df.copy() makes a working copy so the original is kept; params holds the numbers the record needs; the two new columns leave salary unchanged; and the guard prevents the silent NaN column.

Reading: Han §2.2, §2.5; Tan §2.3.

Part 5

The module on one page

1. Meaning (L11)

Storage type ≠ meaning; metadata supplies meaning. Nominal (counts, mode) → binary (proportions) → ordinal (+ median) → interval (+ mean, differences) → ratio (+ ratios). A statement is meaningful only if it survives allowable relabelling. Discrete/continuous is separate. Quality = fitness for a stated use: accuracy, completeness, consistency, timeliness, believability, interpretability.

2. Profile and describe (L12)

Profile: shape, dtypes, isna().sum(), describe(), value_counts(), documented rules. isna() misses coded missing values. Mean (all magnitudes; totals) vs median (middle; robust). Quartiles by stated method (pandas linear: 49.25, 54, 64.75). IQR = Q3 − Q1. Fences Q1 − 1.5 IQR, Q3 + 1.5 IQR; strictly beyond = flag. Detect, record, ask.

3. Missing values (L13)

Kinds: observed, documented marker, not applicable, ambiguous. Convert a marker only if documented and distinguishable. Converting changes representation; filling supplies an estimate. Why missing (MCAR/MAR/MNAR) decides what is defensible. Retain, delete, constant, mean/median: each changes and assumes something. Fills pile up at one value and shrink spread. Log: finding, evidence, action, assumption, affected data, unresolved. Recorded ≠ defensible.

4. Scaling (L14)

σ = root-mean-square distance from the mean, in the attribute's unit; state the divisor (course: N, ddof=0; pandas default N − 1). Min–max: (v − min)/(max − min), position in range. Z: (v − x̄)/σ, SDs from mean, unit-free, unbounded. Compute parameters once, record, reuse; inverse maps recover originals. Rescaling keeps order and shape; it does not remove outliers or make data normal. Check for zero denominators.

Formulas

QuantityFormulaSalaries
Meanx̄ = Σxi / N696 / 12 = 58
Medianmiddle value; average of two middle values if N is even(52 + 56) / 2 = 54
Quartiles (pandas linear)position (N − 1)p, interpolate49.25, 64.75
IQR, rangeQ3 − Q1; max − min15.5; 80
FencesQ1 − 1.5·IQR, Q3 + 1.5·IQR26.0, 88.0 → 110 flagged
Variance, σ (N)Σ(xi − x̄)2 / N, its square root379.17; 19.47
s (N − 1)√(Σ(xi − x̄)2 / (N − 1))20.34
Min–max(v − min) / (max − min); inverse min + v′(max − min)52 → 0.275
Z-score(v − x̄) / σ; inverse x̄ + zσ110 → 2.67
Know what a column means. Look before you change. Name what is unknown and why. State every assumption, record every parameter, and remember that rescaling changes the axis, not the data.