Decide when to look at the data
Before you calculate or model anything, you look at the data: you count it, summarise it and plot it. That habit is called exploratory data analysis (EDA).
Why look? A summary squeezes a whole column into one number, and very different data can share the same numbers. In Anscombe's quartet (1973) four small datasets all have mean of x 9, mean of y 7.50 and correlation r = 0.816, with the same fitted line y = 3.00 + 0.500x. Plotted, one is a straight line and another a curve:
John Tukey's 1977 book made this “look first” approach a method.
Running example. Your lecturer hands you study.csv: twelve student records with hours studied per day, sleep per night, tutorial group and exam score. You will carry it through every step.
A classmate says: “Group A and group B in study.csv have the same mean score and the same correlation between hours and score, so I can skip the plots.” What do you reply?
- The claim assumes that a few summary numbers describe the whole dataset.
- Anscombe's quartet is the counter-example: four sets with mean of x 9, mean of y 7.50, r = 0.816 and line y = 3.00 + 0.500x.
- Plotted, they are a straight line, a curve, a line with one odd point and a vertical stack.
- So the answer is B: plot both groups before trusting the summaries. That is EDA.
Tell numeric from categorical columns
A table has one row per case (here: one student) and one column per variable. Before anything else you ask of every column: what kind of values does it hold?
A numeric variable is a measured amount: you can add it, average it, plot its shape. A categorical variable is a label or group: you count how often each label occurs. An id is written with digits but only names the row; its average means nothing.
In pandas the first look is df.shape (rows, columns), df.dtypes (the type of each column) and df.head() (the first rows). For study.csv, df.shape gives (12, 5).
Click the header of every column that holds a numeric variable you could sensibly average. Click again to unselect.
NaN = empty cell (not a number)
- id: digits, and pandas stores it as
int64, but it only names the student. Not a variable to average. - hours: hours studied per day, a measured amount → numeric (
float64). - sleep: hours of sleep per night → numeric. Its two NaN cells do not change that.
- group: tutorial group A, B or C → categorical (
object). You count the labels. - score: exam score → numeric.
- Answer: hours, sleep, score.
Count the missing values
An empty cell is a missing value; pandas shows it as NaN. Gaps are rarely spread evenly: usually one or two columns hold almost all of them, so you count them per column with df.isna().sum().
The share of a column that is missing is
Mini-example (Kaggle Titanic, from the Blueprint): 891 passengers, 177 without an Age → 177 ÷ 891 = 19.9 % of the Age column.
The share tells you what to do next: a small share can be filled, a column that is mostly empty is usually dropped.
In the raw study.csv below, what percentage of the sleep column is missing?
- NaN cells in sleep: the students with id 4 and id 9 → 2.
- Rows in the raw file: 12 (the repeated row is still there; we have not cleaned yet).
- 2 ÷ 12 = 0.1667 → 16.7 %.
- For comparison, the whole table: 3 empty cells (2 in sleep, 1 in score) out of 12 × 5 = 60 cells = 5 %. A small table-wide share can hide a column that is badly hit.
Put the EDA routine in order
EDA moves through three kinds of stage: inspect what you have, clean what is broken, explore what it means. Like checking a second-hand car: look it over, fix the flat tyre, then take the test drive.
Two rules fix the order. Count before you fix: if you fill the gaps first you can no longer see how many there were. Clean before you summarise: a repeated row is counted twice in every mean.
And what you find is a set of questions, not proof: you check them later on new data (confirmatory analysis).
Put the six actions for study.csv in the order you do them (first at the top). Use ▲ and ▼; they work with the keyboard too.
- Summarise each column:
df.describe()and the five-number summary - Count missing cells and duplicate rows
- Write down what you found as questions to confirm on new data
- Load the file and check its size and column types
- Plot distributions and relationships
- Drop the repeated row and decide, column by column, how to handle the gaps
- inspect Load the file and check its size and column types (
df.shape,df.dtypes). - inspect Count missing cells and duplicate rows (
df.isna().sum(),df.duplicated().sum()). - clean Drop the repeated row and decide per column how to handle the gaps.
- explore Summarise each column.
- explore Plot distributions and relationships.
- explore Write the findings down as questions to confirm on new data.
Predict what one wild value does to the mean
Cleaning study.csv: 12 rows − 1 duplicate = 11, − 1 row without an exam score (the column you want to explain) = 10 students. The one sleep gap left is filled later.
The mean is the sum ÷ n. The median is the middle of the sorted values (with an even n, the average of the two middle ones). One extreme value drags the mean a long way; the median barely moves. That is why EDA reports both.
Hours studied per day of the 10 students:
Sorted, the middle two are 3 and 3.5, so the median is 3.25. Forty hours a day is impossible, but first see what it does.
Set the slider to your prediction of the mean hours of these 10 students, then press Check to reveal the true value.
Accepted within ±0.5 h. The true mean is revealed on Check, so the first try counts.
- Sum: 2 + 3 + 1 + 4 + 2.5 + 40 + 3.5 + 5 + 1.5 + 4.5 = 67.
- Mean: 67 ÷ 10 = 6.7 h, more than twice the median of 3.25 h.
- The single value 40 adds 40 ÷ 10 = 4 h to the mean on its own.
- If 40 is a typo for 4 (step 7 checks it): sum 67 − 36 = 31, mean 3.1 h, median still 3.25 h. The median did not care; the mean did.
Your turn: find the five-number summary
The five-number summary is min, Q1, median, Q3, max: what a box plot draws and what df.describe() prints. The quartiles Q1 and Q3 cut off the lowest and highest quarter.
pandas finds the p-th quantile at position p · (n − 1) of the sorted list, counting positions from 0. A position between two values lies that fraction of the way between them.
Mini-example: 2, 4, 6, 8, 10 (n − 1 = 4). Q1 at 0.25 · 4 = 1 → 4; median at 2 → 6; Q3 at 3 → 8. A position of 2.25 would mean “a quarter of the way from the value at 2 to the value at 3”.
Exam scores of the 10 cleaned students: 58, 64, 50, 71, 62, 66, 68, 77, 55, 74. Min = 50, max = 77. Find the other three numbers with the pandas rule.
- Sorted, positions 0 to 9: 50, 55, 58, 62, 64, 66, 68, 71, 74, 77. n − 1 = 9.
- Median: position 0.5 · 9 = 4.5 → halfway between 64 and 66 = 65.
- Q1: position 0.25 · 9 = 2.25 → 58 + 0.25 · (62 − 58) = 58 + 1 = 59.
- Q3: position 0.75 · 9 = 6.75 → 68 + 0.75 · (71 − 68) = 68 + 2.25 = 70.25.
- Summary: 50 · 59 · 65 · 70.25 · 77, so IQR = 70.25 − 59 = 11.25. (The textbook “median of each half” method gives Q1 = 58 and Q3 = 71; both are in use, pandas uses the one above.)
Fence the outliers with 1.5 × IQR
EDA flags a value as a suspected outlier when it lies beyond Tukey's fences, built from the middle half of the data so the odd value cannot move the ruler:
fences = Q1 − 1.5·IQR , Q3 + 1.5·IQR
A flagged value is investigated, not deleted: a typo is corrected, a real extreme is kept and reported.
The 10 hours values from step 5, sorted: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 40. With the rule from step 6: Q1 (position 2.25) = 2.125 and Q3 (position 6.75) = 4.375.
What is the upper fence for hours studied per day? Any value above it is flagged.
- IQR = 4.375 − 2.125 = 2.25.
- 1.5 × IQR = 1.5 × 2.25 = 3.375.
- Upper fence = 4.375 + 3.375 = 7.75 h; lower fence = 2.125 − 3.375 = −1.25 h.
- 40 > 7.75, so 40 is flagged. You check the student's form: it says 4.0. It was a typo, so you correct it to 4 (mean 6.7 → 3.1 h, step 5).
Match each question to its plot
Which plot you need depends on how many variables you look at and whether they are numeric or categorical (step 2).
| you look at | draw |
|---|---|
| one numeric: its shape | histogram (or a box plot) |
| one categorical: how many of each | bar chart of counts |
| two numeric: do they move together? | scatter plot |
| numeric split by a category | box plot per group |
Like a doctor who first checks each measurement on its own, then pairs such as height and weight.
For each question about the cleaned study.csv, choose the plot to draw first.
- (a) one numeric variable, its shape → histogram.
- (b) two numeric variables → scatter plot of score against hours.
- (c) one categorical variable → bar chart of counts.
- (d) numeric split by a category → box plot per group.
- A pie chart of scores fits none: scores are amounts, not shares of a whole.
Read a correlation without fooling yourself
The correlation r, between −1 and 1, measures how closely two numeric variables follow a straight line together:
Three cautions. One extreme point can make or break r. A perfect U-shape gives r ≈ 0, so “near 0” does not mean “unrelated”. And r means “move together”, never “cause”.
Scanning many pairs also finds things by luck: 20 columns give 20 × 19 ÷ 2 = 190 pairs, and at α = 0.05 about 190 × 0.05 = 9.5 look “significant” in pure noise. EDA findings are hypotheses to confirm.
With the typo 40 still in, r(hours, score) for the 10 students is 0.17. After correcting it to 4 (step 7), r = 0.98. Which conclusion is sound?
- With 40: Σ(dx·dy) = 154.0, Σdx² = 1247.1, Σdy² = 652.5 → r = 154.0 ÷ √(1247.1 × 652.5) = 154.0 ÷ 902.1 = 0.17.
- Corrected (mean hours 3.1, mean score 64.5): Σ(dx·dy) = 100.0, Σdx² = 15.9, Σdy² = 652.5 → r = 100.0 ÷ 101.9 = 0.98.
- One value moved r from weak to very strong: r is sensitive to extreme points.
- A strong r is still not a cause, and 10 students are few. Answer B: write it down as a question to test on new data.
Write the pandas lines
pandas reads the table into a DataFrame df; seaborn draws the plots. Five DataFrame methods cover steps 3 to 6:
- isna
- True where a cell is missing;
.sum()counts them per column - duplicated
- True for a row that repeats an earlier row
- dropna
- drops rows with gaps;
subset=limits it to some columns - median
- the middle value of a column (ignores NaN)
- describe
- count, mean, std, min, Q1, median, Q3, max per numeric column
Filling a gap with the column median is called imputation.
Complete the EDA script for study.csv. Type the method name only.
import pandas as pd import seaborn as sns df = pd.read_csv("study.csv") df.shape # (12, 5) df.().sum() # missing cells per column df.().sum() # repeated rows → 1 df = df.drop_duplicates() df = df.(subset=["score"]) # no target → drop df["sleep"] = df["sleep"].fillna(df["sleep"].()) df.() # five-number summary + mean sns.scatterplot(data=df, x="hours", y="score")
df.isna().sum()→ hours 0, sleep 2, group 0, score 1 (isnullis an alias).df.duplicated().sum()→ 1, thendrop_duplicates()leaves 11 rows.df.dropna(subset=["score"])→ 10 rows.df["sleep"].median()→ the median of the 9 known sleep values: sorted 6, 6, 6.5, 7, 7, 7, 7.5, 8, 8 → 7 h fills the gap of student 4.df.describe()prints the five-number summary of step 6 (with pandas' quartile rule) plus count, mean and std.
Put it all together: run EDA on a new file
A second tutorial group sends lab2.csv. Run the whole routine on it: inspect (steps 2–3), clean (step 4), summarise (steps 5–6), fence (step 7), and decide what a flagged value means (steps 7 and 9).
Nothing new here: every part uses one earlier step. Work on paper, top to bottom.
Clean lab2.csv as in study.csv (drop the repeated row and the row without a score), then answer:
- (a) Row 5 repeats student 21; student 25 has no score. 9 − 1 − 1 = 7 rows (students 21, 22, 23, 24, 26, 27, 28).
- (b) Known sleep of the kept rows: 7, 6, 8, 7.5, 5.5, 7 → sorted 5.5, 6, 7, 7, 7.5, 8 → middle two 7 and 7 → 7 h.
- (c) Kept scores sorted: 57, 59, 61, 66, 70, 73, 98; n − 1 = 6. Q1 at 1.5 = (59 + 61) ÷ 2 = 60; Q3 at 4.5 = (70 + 73) ÷ 2 = 71.5; IQR = 11.5; upper fence = 71.5 + 1.5 × 11.5 = 71.5 + 17.25 = 88.75.
- (d) 98 > 88.75 is flagged, but 98 is a possible score (6 h of study a day). A flag means investigate: check the record, keep and report it if genuine.
- Next you would plot (histogram of score, scatter of score against hours) and write your findings as questions to confirm.