…
…
Statistics and Data Analysis Fundamentals · Lesson 19 / 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.
Three kinds of gaps appeared in the quality report: 89 empty delivery days and 24 empty quantities in the raw orders, and 55 empty ages in the customer table. Logistics wants the "mean delivery time" and marketing wants the "mean customer age". Deleting everything is easy, but dropna() cuts the raw file from 902 rows to 792; in this lesson you will find the reason for each gap and decide accordingly.
At the end of the lesson you will fill in the following decision table yourself, and you will be able to produce the number in every row with code:
| Column | Missing | Reason | Decision | Effect |
|---|---|---|---|---|
delivery_days | 89 | 34 are canceled (the delivery never happened); for 55 there is no clear link | Leave the cancellations, fill the 55 with the median and flag them | Mean stays 2.99, standard deviation 1.155 → 1.118 |
quantity | 24 | Amount, unit price, and discount are filled | Calculate (in lesson 20, once prices are numbers) | No estimate, the real value |
age | 55 | More often empty in the organic channel | Fill with the channel median and flag | Mean 33.34 → 33.33, standard deviation 9.01 → 8.57 |
In this lesson you will:
In lesson 18 you made the quality report with isna().sum(). The numbers are there, but we have not done anything about them yet. First let's see what a gap looks like in pandas and why it is dangerous. pandas shows a missing value as NaN ("Not a Number"). In string columns you may see None or NaN; both mean "there is no value here".
Think of a small weather station in a school yard. It records the noon temperature for a week, but the sensor broke for two days and those days stayed empty:
import pandas as pd import numpy as np temperature = pd.Series([18, 21, np.nan, 20, 19, np.nan, 20.5]) print(temperature.mean()) print(temperature.count(), len(temperature)) print(temperature.isna().sum())
Output19.7
5 7
2mean() returned 19.7 degrees without any warning. The calculation is not wrong, but it is the mean of five days, not seven. mean(), sum(), median(), and std() skip missing values by default. This is useful (if every gap gave an error, you could never make a summary), but it is also dangerous: you cannot trust a result if you do not know how many values it was calculated from. If the two broken days had been the hottest days of the week, the real mean would be above 19.7, and you could not tell from the number.
So use two tools together. count() gives the number of filled values; len() gives the number of all rows. The difference is the number of missing values. To count directly, isna() makes True/False for every cell, .sum() counts the True values, and .mean() gives their share (the rule from lesson 7: "the mean of a boolean column is a proportion").
The first idea that comes to mind is to look for a missing value with the equals sign. Predict what this code prints:
What does this code print?
import numpy as np print(np.nan == np.nan)
This odd rule of NaN is on purpose. You cannot know if two unknown values are equal: was the temperature on the two broken days the same? We do not know. So == always gives False, and you need isna() to count missing values.
Follow what mean() does inside, step by step, in plain Python. The list shows the gaps with None; the loop counts the gaps and takes the mean of the filled values only. g is None asks "is g empty?". After you watch it, put one more None in the list (for example, write None in place of 21) and see how the number of filled values and the mean change.
Run the code line by line: see which line runs next, the variable boxes and the output.
days = [18, 21, None, 20, 19, None, 20.5] missing = 0 filled = 0 total = 0 for g in days: if g is None: missing = missing + 1 else: filled = filled + 1 total = total + g print("Missing:", missing) print("Filled:", filled, "/ Total days:", len(days)) print("Mean:", total / filled)
Before you decide what to do with a gap, ask this question: what do the missing rows look like in another column? If the missing rows are spread randomly, they look the same as the filled rows in other columns. If they pile up in one status or group, that column points to the reason for the gap.
Let's look at the 89 empty delivery days in the raw orders. We find the orders with "cancel" in the status using str.contains (lesson 6). The spelling of the status column is mixed ("canceled", "Canceled"), so we search for the piece "ancel", which does not change with an upper or lower case C. We will fix the spellings in lesson 20.
import pandas as pd h = pd.read_csv("orders_raw.csv") missing = h[h["delivery_days"].isna()] print(len(missing)) print(missing["status"].str.contains("ancel").value_counts())
Output89
status
False 55
True 34
Name: count, dtype: int6434 of the 89 gaps are in canceled orders. There are 34 canceled orders in the raw file in total, so the delivery day is empty in all the cancellations. This is not a data error: a canceled order is never delivered, so it has no delivery day. We call this a structural gap: the value was not lost, it never existed. The remaining 55 gaps are in completed or returned orders, and these are real gaps. The parcel was delivered, but the time was not recorded.
You can ask the same question with proportions: in each status, what share of delivery days is empty? In the cell below, the share is 1.000 for the canceled rows and between 0.035 and 0.135 for the other statuses. Then write carrier in place of status: are the shares close to each other for the three carriers?
Try it now· not graded; doesn't affect progress
After removing the cancellations, the real share of gaps is 0.067, 0.068, and 0.055 for the carriers. The difference is small: the gaps do not pile up at one carrier. This does not prove that the remaining 55 gaps are random (they may depend on a column we did not check), but in the columns we looked at there is no clear link. This is what an analyst can do: look at the columns that come to mind and write down what you find.
Missing values fall into four kinds by their reason. Statisticians also name them with English abbreviations; here we use everyday names, and the abbreviations are in brackets for information only.
Match each case with its kind:
What is the kind of gap in each case?
For each row, pick its match from the list, then check.
When the kind is clear, the decision is mostly clear too. Read the decision tree below from top to bottom:
A structural gap is left: if you fill the delivery day of a canceled order, you make up a delivery that did not happen. A gap that can be calculated is calculated: no estimate is needed. A gap that is random and small can be deleted or filled with the median; neither changes the result much. A gap that depends on a group is filled with the group median and flagged; plain deleting shows that group smaller than it is in the data. For a gap that depends on the value itself, none of the simple methods can fix the result fully; the thing to do is to write the gap clearly in the report.
Deleting has its own trap too. dropna() with empty brackets looks at all columns: it deletes any row that has an empty cell in any column. To look at the gaps of only one column, write dropna(subset=["delivery_days"]). In the raw file the difference is big: h.dropna() keeps 792 of 902 rows (110 rows go: 89 delivery gaps, 24 quantity gaps, minus 3 rows that have both), and h.dropna(subset=["delivery_days"]) keeps 813. When you calculate delivery time, there is no reason to throw away the 21 orders with an empty quantity.
Now meet the request from logistics yourself:
Logistics wants the mean delivery time. The raw file has 89 empty delivery days: 34 are canceled, and 55 are delivered orders whose time was not recorded. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
You decided to fill; but with which value? There are three common options: 0, the mean, and the median. Let's see their effects on a small list: for two of seven deliveries, the time is not recorded.
import pandas as pd x = pd.Series([2, 3, 3, 4, 7, None, None]) print(x.count(), round(x.mean(), 2), round(x.std(), 2)) print(round(x.fillna(0).mean(), 2), round(x.fillna(0).std(), 2)) print(round(x.fillna(x.mean()).mean(), 2), round(x.fillna(x.mean()).std(), 2)) print(round(x.fillna(x.median()).mean(), 2), round(x.fillna(x.median()).std(), 2))
Output5 3.8 1.92
2.71 2.43
3.8 1.57
3.57 1.62Read the lines in order. If you do not fill anything, the mean of five values is 3.8 and the standard deviation is 1.92. Filling with 0 pulls the mean down to 2.71: two parcels are counted as if they arrived in "0 days". Here 0 does not mean "unknown"; it is a real and very small value, and it pushes the mean down and also makes the spread bigger. Filling with the mean does not change the mean (3.8), because the added values sit right in the middle; but the standard deviation drops from 1.92 to 1.57. Filling with the median moves the mean a little (the median is 3, below the mean of 3.8) and again makes the standard deviation smaller (1.62).
Why does the spread get smaller? Remember lesson 14: the standard deviation is the typical distance of the values from the mean. When you put two new values exactly on the mean or the median, you add two observations with almost zero deviation. The divisor gets bigger, the sum of squares stays almost the same, and the result shrinks. You make up a consistency that is not in the data. With few gaps the effect is small, and with many gaps it is misleading.
Change the method below and watch the three numbers:
Two of seven deliveries are unrecorded. How does the filling method change the count, the mean, and the standard deviation?
Pick a value; predict the output first, then look.
1import pandas as pd2method = "leave"3x = pd.Series([2, 3, 3, 4, 7, None, None])4if method == "zero":5 x = x.fillna(0)6elif method == "mean":7 x = x.fillna(x.mean())8elif method == "median":9 x = x.fillna(x.median())10print("Values:", x.count())11print("Mean:", round(x.mean(), 2))12print("Standard deviation:", round(x.std(), 2))
Values: 5 Mean: 3.8 Standard deviation: 1.92
Faded lines didn't run with this value. If you leave the gaps, the calculation rests on 5 real values. 0 pulls the mean down and makes the spread bigger. The mean and the median add values close to the center, so they make the standard deviation smaller (1.92 → 1.57 and 1.62): a consistency that does not exist appears. No filling adds new information.
Now let's apply the decision in the case. We remove the cancellations (their delivery day will stay empty), and in the remaining 868 orders there are 55 real gaps. The order matters: flag column first, then filling. After you fill, you can no longer see which rows were filled.
import pandas as pd h = pd.read_csv("orders_raw.csv") canceled = h["status"].str.contains("ancel") d = h[~canceled] d["delivery_missing"] = d["delivery_days"].isna() print("Missing:", d["delivery_missing"].sum(), "| median:", d["delivery_days"].median()) print("Before:", round(d["delivery_days"].mean(), 3), round(d["delivery_days"].std(), 3)) d["delivery_days"] = d["delivery_days"].fillna(d["delivery_days"].median()) print("After:", round(d["delivery_days"].mean(), 3), round(d["delivery_days"].std(), 3))
OutputMissing: 55 | median: 3.0
Before: 2.988 1.155
After: 2.988 1.118The median is 3 days, very close to the mean of 2.988, so the mean stayed the same up to the third decimal. The standard deviation went down from 1.155 to 1.118: adding 55 values of "exactly 3 days" narrowed the spread a little. That filling did not change the mean does not mean it is "harmless"; the effect is hidden in the spread.
The filling line was written with an assignment: d["delivery_days"] = d["delivery_days"].fillna(...). fillna returns a new column; it does not change the old one by itself, and if you do not assign the result back to the old name, the gaps stay in place. Try it yourself; if you fill with 0 instead of the median, you will see the mean fall to 2.80:
Try it now· not graded; doesn't affect progress
The 55 empty ages in the customer table tell a different story. Let's look at the share of gaps by acquisition channel:
import pandas as pd c = pd.read_csv("customers.csv") c["age_missing"] = c["age"].isna() print(c.groupby("acquisition_channel")["age_missing"].mean().round(3)) print(c.groupby("acquisition_channel")["age"].median())
Outputacquisition_channel
ads 0.091
organic 0.132
referral 0.038
social media 0.067
Name: age_missing, dtype: float64
acquisition_channel
ads 33.0
organic 34.0
referral 31.0
social media 32.0
Name: age, dtype: float64For customers from the organic channel, 13.2% of ages are empty; for those who came by referral, only 3.8%: a difference of about 3.5 times. The gap depends on the channel. The channels also differ in age: the median age of organic customers is 34 and of referral customers 31. Most of the gaps come from an older group.
Age is empty more often in the organic channel, and organic customers are older (median 34). If we fill the gaps with the overall median of all customers (33), what happens to the mean age of the organic group?
This is why we fill with the group median: each customer's empty age gets the median of their own channel. The transform("median") from lesson 7 puts the median of each row's group on that row; fillna then fills only the empty cells with it:
import pandas as pd c = pd.read_csv("customers.csv") c["age_missing"] = c["age"].isna() before = c["age"] c["age"] = c["age"].fillna(c.groupby("acquisition_channel")["age"].transform("median")) print(c["age"].isna().sum()) print("Before:", round(before.mean(), 2), round(before.std(), 2)) print("After:", round(c["age"].mean(), 2), round(c["age"].std(), 2))
Output0
Before: 33.34 9.01
After: 33.33 8.57No gaps are left. The mean is almost the same (33.34 → 33.33), and the standard deviation went down from 9.01 to 8.57: giving 55 customers the middle age of their own channel narrowed the spread again. The group median is better than the overall median, but it is not magic. Are the people in the organic channel who did not write their age really the typical customers of that channel? Maybe the ones who did not write their age are even older (a gap that depends on the value itself); we cannot know this from the data. That is why the flag column stays and the report states the filling clearly.
The best filling is not guessing. In the raw file, the quantity is empty in 24 orders, but in the same rows the amount, unit price, and discount are filled. The amount is made like this: amount = quantity × unit_price × (1 − discount). From this the quantity can be found exactly: quantity = amount / (unit_price × (1 − discount)). This is not an estimate, it is a calculation; the filled value is the real value itself.
In the raw file the unit prices are saved as text (for example 72.75 and 72,75 USD both appear); we will turn them into numbers in lesson 20 and apply the calculation there. For now let's see the idea with a small table of four rows written by hand:
import pandas as pd t = pd.DataFrame({ "amount": [119.90, 62.96, 22.45, 44.85], "unit_price": [59.95, 69.95, 22.45, 14.95], "discount": [0.0, 0.1, 0.0, 0.0], "quantity": [None, None, 1, 3], }) t["quantity_computed"] = t["quantity"].isna() calc = t["amount"] / (t["unit_price"] * (1 - t["discount"])) t["quantity"] = t["quantity"].fillna(calc.round()) print(t) print(t["quantity"].isna().sum())
Output amount unit_price discount quantity quantity_computed
0 119.90 59.95 0.0 2.0 True
1 62.96 69.95 0.1 1.0 True
2 22.45 22.45 0.0 1.0 False
3 44.85 14.95 0.0 3.0 False
0In the first row, $119.90 / $59.95 = 2 units; in the second, $62.96 / ($69.95 × 0.9) is about 1 unit. Because cent rounding can leave small fractions, we rounded the result to an integer with round(). The filled rows (quantity 1 and 3) were not touched; fillna fills only the gaps.
Now put the same steps in order yourself:
Put the lines that fill the empty quantities by calculation in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
A filled value is not a real measurement. The moment you fill it, the data stops telling you this; a real delivery of 3 days and a 3 written from the median look the same. This is why you add a flag column before every filling (delivery_missing, age_missing, quantity_computed). Thanks to the flag, at the end of the analysis you can ask, "If I remove the filled rows, does the result change?"
The same honesty applies to the report. When you give a mean, write how many real observations it rests on and what you did. The sentence for logistics: "Mean delivery time is 2.99 days (813 deliveries; 55 gaps filled with the median, 34 canceled orders excluded)." The sentence for marketing: "Mean customer age is 33 (the age is known for 522 customers; the age of 55 customers was filled with the channel median, and the gaps are more frequent in the organic channel)." The reader sees both the result and the limit of the result in the same sentence.
Let's compare the deletion that looks at the whole table with the one that looks at only the delivery column.
import pandas as pd h = pd.read_csv("orders_raw.csv") print(len(h)) print(len(h.dropna())) print(len(h.dropna(subset=["delivery_days"]))) print((h["quantity"].isna() & h["delivery_days"].isna()).sum())
Output902
792
813
3dropna() deletes 110 rows: 89 empty delivery days + 24 empty quantities − 3 rows where both are empty. For someone interested in delivery time, the right deletion is the second one: only the 89 rows that are empty in that column go.
Do not type the numbers in the report by hand; let the code produce them, so that if a number changes, the sentence changes too.
import pandas as pd c = pd.read_csv("customers.csv") real = c["age"].count() missing = c["age"].isna().sum() c["age"] = c["age"].fillna(c.groupby("acquisition_channel")[].transform()) (, (c[].mean(), 1), + (real), , missing, )
Counting missing values with ==:
Output(h["quantity"] == np.nan).sum() # gives 0NaN is not equal to anything, even to itself, so the comparison returns False in every row; the result is 0 and the column looks like it has no gaps at all. In the raw file there are really 24 empty quantities. The correct way is h["quantity"].isna().sum().
isna() (== np.nan always gives False); mean, sum, median, and std skip them silently, so check how many values the result rests on with count().dropna() looks at all columns, so write subset for a single column.inplace), and write the number of real observations and the method in the report.Next lesson: The same thing written in different ways ("Canceled", "canceled"), duplicate records, and prices stored as text; you will do the consistency check of the raw file and apply the quantity calculation there.
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.
OutputMean age 33.3 (522 real, 55 filled)count() and isna().sum() were taken before filling; if they were taken after, they would say 577 real, 0 filled.