…
…
Statistics and Data Analysis Fundamentals · Lesson 18 / 44 · Dirty data and missing values
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The orders.csv file you have used so far was actually a cleaned copy; the original export from the system is in orders_raw.csv, and it has 902 rows, not 885. Accounting asks: "The raw file gives $77,036.05 in revenue, and your report says $66,843.57. Which one is right?" In this lesson you will find what is broken in the raw file without touching it, and you will write the first half of the answer: a quality report.
At the end of the lesson you will fill in a table like this one with your own code. For now the row counts are empty:
Outputcolumn problem rows action
date three different formats ? convert to one format
device same value spelled differently ? standardize
quantity empty cell ? find the reason
order_id exact duplicate row ? drop the duplicate
customer_id TEST order ? leave out of the analysisThis table is the base of the answer for Accounting: "The raw revenue is not reliable because of these problems; the clean revenue will be ready after these steps."
In this lesson you will:
"Garbage in, garbage out" is the first rule of data analysis. Even the best method cannot give a correct result from data that is recorded wrongly, written twice, or incomplete. Let's repeat Accounting's question in a few lines:
import pandas as pd raw = pd.read_csv("orders_raw.csv") clean = pd.read_csv("orders.csv") print(len(raw), round(raw["amount"].sum(), 2)) print(len(clean), round(clean["amount"].sum(), 2))
Output902 77036.05
885 66843.57Both files describe the same orders from the same period, and the difference is $10,192.48. The total in the raw file was calculated without any error message. pandas does not tell you "some rows in this column were written twice" or "an extra zero was added to this amount"; it only adds up the numbers it is given. Code that runs does not show that the data is correct.
raw["amount"].sum() ran on the raw file with no error and gave 77036.05. Can we trust this revenue?
This is why experienced analysts do not start the analysis as soon as they get a new file; they scan it first. This lesson is entirely about scanning: we will not fix anything, we will only find and count. You will do the fixing in the next three lessons.
Saying "the data is dirty" is not enough. You need to name what is dirty, because each problem has a different fix. Data quality is usually checked with five questions:
Validity and accuracy are the pair that people mix up most often. Validity asks, "Can this value exist?" $3,299.00 can be the amount of an order; it does not break any rule. Accuracy asks, "Is it really so?" The real amount of that order is $329.90. A valid value can still be wrong.
Which quality dimension does each problem break?
For each row, pick its match from the list, then check.
The five dimensions are not only for e-commerce data. A high school club collected a sign-up form for a trip, and the club president typed the list into a table by hand. It has eight rows, so you can read it by eye:
import pandas as pd club = pd.DataFrame({ "name": ["Maya", "Marco", "Zara", "Kai", "Marco", "Amara", "Ethan", "Lena"], "grade": ["10-A", "10-A", "11-B", "10a", "10-A", "11-B", "10-A", "11-B"], "birth_year": [2010, 2010, 2009, 2090, 2010, 2001, 2010, 2009], "age": [16, 16, 17, 16, 16, 16, 16, 17], "email": ["maya@example.com", "marco@example.com", None, "kai@example.com", "marco@example.com", "amara@example.com", None, "lena@example.com"], }) print(club)
Output name grade birth_year age email
0 Maya 10-A 2010 16 maya@example.com
1 Marco 10-A 2010 16 marco@example.com
2 Zara 11-B 2009 17 NaN
3 Kai 10a 2090 16 kai@example.com
4 Marco 10-A 2010 16 marco@example.com
5 Amara 11-B 2001 16 amara@example.com
6 Ethan 10-A 2010 16 NaN
7 Lena 11-B 2009 17 lena@example.comAll five dimensions are here. The emails of Zara and Ethan are empty (completeness). Kai appears to be born in 2090; such a birth year cannot exist (validity). Kai's grade is written as "10a" while the others are written as "10-A" (consistency). Marco is in two rows with exactly the same information (uniqueness). Amara's age is 16 but her birth year is 2001; one of the two is wrong (accuracy). None of them stands out alone; they appear when you ask column by column.
The club president will rent a trip bus with this 8-row list. What should they do?
Pick an option and see what happens. There are no points; you can try the other options too.
You found these problems by eye in eight rows. Bazaar's raw file has 902 rows and 13 columns; you cannot scan it by eye. For that you need a method that asks the same five short questions of every column: a profile scan. We will ask the questions one by one in code: what is the type, how many are missing, how many different values are there, what are the smallest and largest values, and are there repeats?
The first question is "what type was each column read as?" The dtypes you have known since lesson 4 works like a detective here, because if a type does not match what you expect, there is something inside the column. The second question is "how many empty cells are in each column?": isna().sum(). isna() gives True or False for every cell to answer "is it empty?", and sum() counts the Trues. You will see the details in the next lesson; for now we only count.
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h.shape) print(h.dtypes[["quantity", "unit_price", "amount", "delivery_days"]]) missing = h.isna().sum() print(missing[missing > 0])
Output(902, 13)
quantity float64
unit_price str
amount float64
delivery_days float64
dtype: object
quantity 24
delivery_days 89
dtype: int64There are three clues. First, unit_price is a price column, but it was read as str (string). If a column that should be a number has the string type, there is at least one value in it that does not look like a number; a single "164,95 USD" turns the whole column into strings. Second, the quantity column should be integers but was read as float64 (float). An order cannot contain 1.5 units of a product, so why a float?
The quantity column, which should be integers, looks like float64. What does this point to?
The third clue is in the missing counts: quantity has 24 empty cells and delivery_days has 89. But be careful: "missing" does not only mean an empty cell. In a moment you will see rows whose cells are full but which should not enter the analysis (like test orders). An empty cell is only the most visible form of missing.
Below, ask the same two questions yourself. Then change the file to the customers table and run the same scan there:
Try it now· not graded; doesn't affect progress
In a categorical column, you often know in advance how many different values there should be. In Bazaar there are two device types (mobile, desktop), three order statuses (completed, returned, canceled), three carriers, and five categories. The third question of the scan compares this expectation with reality: nunique() gives the number of different values, and value_counts() gives how many times each value appears.
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h[["device", "status", "carrier", "category"]].nunique()) print(h["device"].value_counts())
Outputdevice 8
status 7
carrier 3
category 5
dtype: int64
device
mobile 434
desktop 291
Mobile 47
Desktop 43
mobile 27
desktop 23
MOBILE 20
desk top 17
Name: count, dtype: int64Carrier (3) and category (5) are as expected; they are clean. Device, however, has 8 different values instead of 2. Look at the list carefully: "mobile" appears twice. One is "mobile" and the other is "mobile " (there is a space at the end); they look almost the same on the screen, but for the computer they are two different strings. " desktop" was written with a space at the start, "desk top" has a space in the middle, and "Mobile" starts with a capital letter. The capital "MOBILE" is the sneakiest: it ends with an invisible character, a zero-width space. It takes no room on the screen, it often arrives with copy and paste, and strip() and lower() do not remove it, so even "MOBILE" and "MOBILE" can be different values. All of them describe the same two devices. This is a consistency problem: 434 + 291 = 725 rows have the expected spelling, and the remaining 177 rows were recorded with a different spelling. The status column has a similar picture: "completed" appears 690 times, "Completed" 76 times, "complete" 37 times, and "Returned" and "Canceled" with a hidden character 8 and 4 times, 7 spellings in all.
Why does this problem matter? If you report orders by device with value_counts(), mobile orders look like 434; in reality they are 434 + 47 + 27 + 20 = 528. An inconsistent spelling splits the count silently.
In the small example below, see how removing the spaces at the end (str.strip(), lesson 6) changes the number of different values. The cleaning here is only to see what the problem is; you will clean the real file in lesson 20.
There are five device spellings. How does removing the spaces at the start and end change the number of different values?
Pick a value; predict the output first, then look.
1import pandas as pd2clean = False3s = pd.Series(["mobile", "Mobile", "mobile ", "MOBILE\u200b", "desktop"])4if clean:5 s = s.str.strip()6print("Distinct values:", s.nunique())7print(s.value_counts())
Distinct values: 5 mobile 1 Mobile 1 mobile 1 MOBILE 1 desktop 1 Name: count, dtype: int64
Faded lines didn't run with this value. When the space is removed, "mobile " and "mobile" merge: 5 values drop to 4. "Mobile" and "MOBILE" are still separate, because a capital letter and an invisible character are not spaces. The hidden character makes this a little harder; you will solve it in lesson 20.
For numeric columns, describe() is the fastest way to look at the smallest and largest values. Validity problems usually hide at the ends: a negative quantity, an amount of $1, a value that is impossibly large.
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h[["quantity", "amount", "delivery_days"]].describe().round(1))
Output quantity amount delivery_days
count 878.0 902.0 813.0
mean 1.4 85.4 3.0
std 0.8 166.4 1.2
min -1.0 1.0 1.0
25% 1.0 22.4 2.0
50% 1.0 45.0 3.0
75% 2.0 89.8 4.0
max 4.0 3299.0 7.0Read it line by line. The smallest quantity is −1: an order cannot be placed with a negative quantity, so this is a validity problem. delivery_days runs from 1 to 7 days; it looks normal. The smallest amount is 1.0, which means $1.00; Bazaar sells nothing for $1. Let's look at these rows:
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h[h["amount"] < 5][["order_id", "customer_id", "unit_price", "amount"]])
Output order_id customer_id unit_price amount
70 T00002 TEST 1.00 1.0
160 T00003 TEST 1.00 1.0
870 T00001 TEST 1.00 1.0Three orders belong to a customer named TEST: they are fake orders entered while the system was being tried out. Their cells are not empty and their values are in a valid format, but they do not describe a real customer, and they should not enter the analysis. These rows show why "a missing value is only an empty cell" is the wrong idea.
The largest amount is more interesting: $3,299.00. Look at it in the language of lessons 11–16: the upper quartile is $89.80, so this value is more than 36 times larger, and its z-score is about (3,299 − 85.4) / 166.4 ≈ 19. On a box plot it would appear alone as a point very far away. But is this an error?
In the describe output the largest amount is $3,299.00 and the upper quartile is $89.80. Is this row an error?
If you look at the row, you see 2 units with a unit price of $164.95, an order that should be $329.90; an extra zero was added to the amount. This is an accuracy problem, but describe did not tell you that; it only showed you where to look. The opposite is also true: the same file has amounts that are not extreme but were still written ten times too large (a $6.45 product written as $64.50). An extreme value is not always an error, and an error is not always an extreme value.
The last question is "is the same record there more than once?" duplicated() gives True or False for each row to answer "is there an identical row above this one?", and sum() counts the repeats. Read it together with the number of different values in the key column:
import pandas as pd h = pd.read_csv("orders_raw.csv") print("Rows:", len(h)) print("Exact duplicates:", h.duplicated().sum()) print("Distinct order_id:", h["order_id"].nunique())
OutputRows: 902
Exact duplicates: 14
Distinct order_id: 888These two numbers do not ask the same question. duplicated() counts rows whose columns are all the same: 14 rows are exact copies of another row. order_id.nunique() counts how many different order numbers there are: 888, so 902 − 888 = 14 rows carry a number that was seen before. In this file the two numbers match, but they do not have to. If the same order number had been written twice with a different delivery day, it would not count as an exact duplicate, but the number would still repeat. In the other direction, if two different customers buy the same product at the same price on the same day, their order numbers are different and it is not a repeat. This is why you look at both.
In the same step, check the formats too. Are all the dates in the form 2026-03-15? str.contains (lesson 6) looks for a piece inside a string:
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h["date"].str.contains("-").sum()) print(h["date"].str.contains(".").sum()) print(h["date"].str.contains(".", regex=False).sum()) print(h["unit_price"].str.contains("USD").sum())
Output723
902
117
113723 dates are in the dashed (ISO) format; the other 179 dates are in another format. There is a trap in the second line: you wanted to count the dotted dates but the result is 902, which means all the rows. By default, str.contains reads the piece it looks for as a pattern, and in a pattern a decimal point means "any character"; every date has at least one character, so all of them match. To search for the decimal point as a decimal point, you write regex=False: 117 dates are in the form 29.05.2026. The other 62 dates have slashes, like 3/8/2026. The last line: 113 prices look like "164,95 USD", with a decimal comma and the letters, so they are strings; this is the answer to why the unit_price column was read as str.
The five questions of the scan are the same short code for every new file. Put the lines in the right order:
Put the lines that run the profile scan of the raw file in the right order: read, type, missing, categorical count, duplicates.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
At the end of the scan, you write what you found as a quality report: which column, which problem, in how many rows, and what you plan to do. The report guides the next cleaning steps, and it also tells the person who reads your analysis clearly what the limits of the data are. The report for Bazaar's raw file looks like this:
Outputcolumn problem rows action (lesson)
date two non-ISO formats 179 convert to one format (20)
device inconsistent spelling 177 standardize (20)
status inconsistent spelling 125 standardize (20)
unit_price text with "USD" added 113 convert to number (20)
quantity empty cell 24 find the reason (19)
quantity negative value 2 decide with a business rule (21)
delivery_days empty cell 89 find the reason (19)
whole_row exact duplicate 14 drop the duplicate (20)
customer_id TEST order 3 leave out of the analysis (20)
amount extreme and ten-times values ? decide with a business rule (21)Each row matches a quality dimension, and each has a next step. The numbers in the report are not typed by hand; they come from code, so if the file changes you run the code again.
The most important rule: the raw file does not change. You always clean in a new variable or a new file (like clean = h.copy()). If you make a wrong decision in one step, you can go back to the raw file and start again; if you wrote over the raw file, that way is closed.
Produce the numbers of the report yourself. The code calculates five numbers; you add two lines:
Try it now· not graded; doesn't affect progress
The answer you can give to Accounting's question now: "Do not trust the raw revenue; it has 14 duplicate rows, 3 test orders, and amounts written ten times too large. The clean revenue will be ready after these problems are fixed." The second half of the answer, the fixing, is the work of the next three lessons.
To see that an empty cell is not always an error, look at the status of the orders whose delivery days are empty:
import pandas as pd h = pd.read_csv("orders_raw.csv") empty = h[h["delivery_days"].isna()] print(len(empty)) print(empty["status"].value_counts())
Output89
status
completed 42
canceled 30
Completed 5
complete 5
Canceled 4
returned 2
Returned 1
Name: count, dtype: int64Of the 89 empty cells, 34 (30 + 4) are in canceled orders: a canceled order is not delivered, so it is natural for it to be empty. The remaining 55 are in completed or returned orders; these are a real gap in the records. The same "empty cell" tells two different stories; we will talk about what to do for each in the next lesson. The scattered status spellings here also remind you of the consistency problem.
To see the three date formats in one count, you can give each format a name and count it:
import pandas as pd h = pd.read_csv("orders_raw.csv") iso = h["date"].str.contains("-") dotted = h["date"].str.contains(".", regex=False) slashed = h["date"].str.contains("/") (iso.(), dotted.(), slashed.()) (iso.() + dotted.() + slashed.() == (h))
Starting the analysis directly without a scan. This sentence is wrong:
OutputThe code did not give an error; Bazaar's revenue for the first six months is $77,036.05.In the raw file h["amount"].sum() does not give an error, but because there are 14 repeated rows, 3 test orders, and amounts recorded ten times too large, it produces a wrong revenue. Not getting an error message does not mean that the data is correct. The corrected sentence: "The raw file gives about $77,000, but the file has duplicates, test orders, and wrongly written amounts; I will give the revenue separately after cleaning."
dtypes, isna().sum(), nunique()/value_counts(), describe(), duplicated().sum(); an unexpected type (string price, float quantity) and more different values than expected are signs of a problem, while an extreme value only says "look here".Next lesson: You found the problems. Now you will handle the quietest one, missing values: why are they empty, and what should you do for each?
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output723 117 62
TrueThe sum of the three counts equals the row count: every date is in exactly one of these three formats. If the total were not equal, either a date would match two formats at once or there would be a fourth format; the scan should check this too.