…
…
Statistics and Data Analysis Fundamentals · Lesson 21 / 44 · Consistency and outliers
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.
In the previous lessons the raw file went down to 885 rows: duplicates, test orders, spelling differences, and text prices were cleaned. But total revenue is still $75,900.54, while the clean copy shows $66,843.57, which is $9,056.97 too much. In this lesson you will decide which of the "too big" amounts are errors and which are truly expensive orders.
By the end of this lesson you will be able to produce two results yourself. The first is a decision list: what you did to which rows, and why. The second is a before/after table: the effect of your decisions on the summary numbers.
| Finding | Rows | Decision | Reason | ||
|---|---|---|---|---|---|
| Amount is exactly 10 times the calculated value | 12 | Correct | A shifted decimal point; the right value can be calculated exactly | ||
| Quantity is −1 and the amount matches \ | quantity\ | 2 | Correct (abs) | The minus sign is an entry error; the right quantity is 1 | |
| Above the IQR fence after correcting, and follows the business rule | 73 | Keep | Real and expensive orders (42 of them are Electronics) |
| Rows | Total | Mean | Median | Standard deviation | |
|---|---|---|---|---|---|
| Before | 885 | 75,900.5 | 85.8 | 45.0 | 167.2 |
| After | 885 | 66,843.6 | 75.5 | 45.0 | 101.2 |
In this lesson you will:
An outlier is an observation that stays clearly far from the rest of the data. It can have two very different sources. The first is an error: a wrongly entered amount, a measurement in the wrong unit, a test record. The second is a real but rare event: a customer buying two robot vacuums in one order. Errors are corrected or removed. Real extreme values are often the most interesting part of the analysis, and you do not delete them. So the first thing to do with an outlier is not to delete it. First, understand why it is there.
In lesson 15 you saw that the whisker of a box plot extends at most 1.5 × IQR, and that values beyond the whisker are drawn as single points. The first tool of this lesson is that limit itself. The value 1.5 × IQR below Q1 is called the lower fence, and the value 1.5 × IQR above Q3 is called the upper fence:
Values outside the fences count as outlier candidates. The word "candidate" is chosen on purpose: the rule only tells you where to look. The good thing about this rule is that quartiles are not affected by extreme values. If you double the largest amount, Q1 and Q3 do not move, so the fences do not move either. This is why the rule is robust.
Let's calculate the fences on the clean copy (orders.csv):
import pandas as pd s = pd.read_csv("orders.csv") q1, q3 = s["amount"].quantile([0.25, 0.75]) iqr = q3 - q1 lower = q1 - 1.5 * iqr upper = q3 + 1.5 * iqr print(q1, q3, round(iqr, 2)) print("Lower fence:", round(lower, 2), "| Upper fence:", round(upper, 2)) outliers = s[s["amount"] > upper] print("Outlier candidates:", len(outliers)) print(outliers["category"].value_counts())
Output22.35 83.95 61.6
Lower fence: -70.05 | Upper fence: 176.35
Outlier candidates: 73
category
Electronics 42
Home & Living 16
Clothing 14
Beauty 1
Name: count, dtype: int64The lower fence is negative (−$70.05). No amount is negative, so there are no outlier candidates at the bottom. This is normal for right-skewed data. At the top there are 73 orders, and 42 of them are Electronics. These orders are not errors: we are on the clean copy, and Electronics products are expensive. The rule said "look here", and when we look, we see the expensive products of the store.
Run the code yourself. Then write delivery_days instead of amount and see how the fences change:
Try it now· not graded; doesn't affect progress
For delivery days, the upper fence came out as exactly 7 days, and the longest delivery is also 7 days. One question:
In the clean copy the longest delivery time is 7 days and the upper fence is also 7.0. Why did the rule not flag any delivery as an outlier?
The number 1.5 is not a law of nature. It is a convention. The statisticians who made the box plot popular chose it so that the rule "does not alarm too often, but does not miss a really distant value". If you make the multiplier bigger, the fences move away and fewer values are flagged; values beyond 3 × IQR are sometimes called far outliers. If you make it smaller, more alarms ring. Below are the prices of ten products in a store; change the multiplier:
With a multiplier of 1, 1.5, and 3 on ten product prices, how do the upper fence and the flagged prices change?
Pick a value; predict the output first, then look.
1import pandas as pd2multiplier = 1.53price = pd.Series([12.45, 19.95, 24.95, 37.45, 44.95, 59.95, 74.95, 124.95, 199.95, 449.95])4q1, q3 = price.quantile([0.25, 0.75])5upper = q3 + multiplier * (q3 - q1)6print("Upper fence:", round(upper, 2))7print("Flagged:", price[price > upper].tolist())
Upper fence: 239.01 Flagged: [449.95]
Faded lines didn't run with this value. The quartiles stay the same (Q1 28.075, Q3 112.45); only the distance of the fence changes. With a multiplier of 1, the $199.95 product also raises an alarm; with 1.5 and 3, only $449.95 is left. You write in the report which multiplier you chose.
In lesson 16 you learned the z score: how many standard deviations a value is from the mean. A rule such as "if the z score is greater than 3, it is an outlier" is also common. But this rule goes blind when the extreme value itself makes the mean and the standard deviation larger. Think of ten rental homes in a neighborhood: nine apartments between $425 and $650, and one villa at $2,250.
import pandas as pd rent = pd.Series([425, 450, 475, 500, 525, 550, 600, 625, 650, 2250]) q1, q3 = rent.quantile([0.25, 0.75]) print("Upper fence:", q3 + 1.5 * (q3 - q1)) z = (rent - rent.mean()) / rent.std() print("Mean:", rent.mean(), "| Std:", round(rent.std(), 1)) print("Villa z score:", round(z.iloc[-1], 2))
OutputUpper fence: 825.0
Mean: 705.0 | Std: 548.0
Villa z score: 2.82The IQR rule catches the villa at once: $2,250 is far above the fence of $825. The z rule does not catch it, because the villa pulled the mean from $533 up to $705 and inflated the standard deviation to $548. The villa itself stretched the ruler you use to measure distance, so its own z score stayed below 3. This often happens with data that has few observations and is right-skewed.
The villa costs more than three times the other rents. So why did its z score not pass 3?
Now let's return to the real question, the raw file. The preparation lines repeat the cleaning you did in lessons 18–20: remove duplicates and test orders, convert prices to numbers, and fill missing quantities by calculation. Then we look at two things: what does the IQR rule say, and what does the business rule say?
A business rule is a condition that comes from domain knowledge, and the data must follow it. The amount of an order must be unit price × quantity × (1 − discount); the quantity cannot be negative. A statistical rule says "this value is far from the others". A business rule says "this value cannot be". One is an alarm, the other is evidence.
import pandas as pd def price_to_number(text): text = text.replace(" USD", "") if "," in text: text = text.replace(",", ".") return float(text) # Preparation (lessons 18-20): duplicates, TEST, price, missing quantity r = pd.read_csv("orders_raw.csv").drop_duplicates() r = r[r["customer_id"] != "TEST"] r["unit_price"] = r["unit_price"].map(price_to_number) r["quantity"] = r["quantity"].fillna((r["amount"] / (r["unit_price"] * (1 - r["discount"]))).round()) q1, q3 = r["amount"].quantile([0.25, 0.75]) upper = q3 + 1.5 * (q3 - q1) print("Above the fence:", (r["amount"] > upper).sum(), "| Upper fence:", round(upper, 2)) calculated = (r["unit_price"] * r["quantity"] * (1 - r["discount"])).round(2) ratio = (r["amount"] / calculated).round(1) print(ratio.value_counts()) ten_times = ratio == 10 (, (r.loc[ten_times, ] > upper).()) (r.loc[ten_times & (r[] <= upper), [, , ]])
OutputAbove the fence: 74 | Upper fence: 191.08
1.0 871
10.0 12
-1.0 2
Name: count, dtype: int64
Ten-times rows still above the fence: 10
category unit_price amount
33 Home & Living 16.45 148.1
631 Books 6.45 64.5Read the output line by line. The IQR rule flagged 74 amounts, and the fence is $191.08 (the errors pushed Q3 up a little; on the clean copy it was $176.35). The business rule shows three groups. In 871 rows the amount equals the calculated value (ratio 1). In 12 rows the amount is exactly 10 times the calculated value: this is not a random error but a systematic entry error where the decimal point moved one place, and the right value is known exactly. In 2 rows the ratio is −1: the quantity is negative, but the amount matches unit price × |quantity| exactly, so the minus sign was entered by mistake.
The most useful part is the last lines. Of the 12 errors, 10 are above the fence, but 2 stay below it: a $6.45 book was entered as $64.50, and a $14.80 home item as $148.10. $64.50 is a normal amount for a Bazaar order; it sits inside the box in a box plot. No statistical rule can catch it, because the value is not "far", only "wrong". Only the business rule catches it. The z > 3 rule is even worse: it flags 12 amounts, and only 6 of them are errors (in the Examples section).
Here are four flagged rows and four decisions. Match each row with the right decision:
Which decision is right for each flagged row?
For each row, pick its match from the list, then check.
TESTFor each flagged value, one of four decisions is made. All of them start with the same question: is it certain that this value is an error?
Think of a referee checking a video replay. The referee first looks at the footage, then decides and explains the decision; everyone can see how a goal that counts or does not count changes the score. With outliers the order is the same: first look at the evidence, then decide, then announce the effect of your decision on the result.
Put the order of these decisions together yourself:
Put the steps in the right order when you work with outliers.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now let's apply the decision: the two negative quantities are fixed with abs, and twelve amounts are changed to the calculated value with loc. Before correcting, we keep the old amounts aside under the name before, so we can build the before/after table. A small function produces the table: row count, total, mean, median, and standard deviation.
import pandas as pd def price_to_number(text): text = text.replace(" USD", "") if "," in text: text = text.replace(",", ".") return float(text) # Preparation (lessons 18-20): duplicates, TEST, price, missing quantity r = pd.read_csv("orders_raw.csv").drop_duplicates() r = r[r["customer_id"] != "TEST"] r["unit_price"] = r["unit_price"].map(price_to_number) r["quantity"] = r["quantity"].fillna((r["amount"] / (r["unit_price"] * (1 - r["discount"]))).round()) before = r["amount"].copy() r["quantity"] = r["quantity"].abs() calculated = (r["unit_price"] * r["quantity"] * (1 - r["discount"])).round(2) wrong = (r["amount"] / calculated).round(1) == 10 r.loc[wrong, "amount"] = (r.loc[wrong, "amount"] / 10).round(2) print("Corrected amounts:", wrong.()) summary(a): [(a), a.(), a.mean(), a.median(), a.std()] report = pd.DataFrame([summary(before), summary(r[])], index=[, ], columns=[, , , , ]) (report.(1))
OutputCorrected amounts: 12
rows total mean median std
before 885 75900.5 85.8 45.0 167.2
after 885 66843.6 75.5 45.0 101.2Read the table column by column. The row count did not change: no order was deleted, only wrongly written numbers were corrected. The total went down to $66,843.57. This is exactly the total of the clean copy. The mean went down from $85.8 to $75.5, about $10: twelve inflated amounts were pulling the mean up. The median stayed at $44.95 (shown as 45.0 after rounding to one decimal). This is the rule from lesson 12 in action: the mean is sensitive to extreme values, and the median is not. The standard deviation went down from 167.2 to 101.2; it is also sensitive to extreme values (lesson 14).
Run the code, then add the largest amount to the summary function:
Try it now· not graded; doesn't affect progress
After the correction we are on the clean copy, and the IQR rule still flags 73 orders. They follow the business rule; all of them are real sales. So what happens if we delete them? This is the most common misunderstanding about outliers: "if it is an outlier, delete it". Let's see the effect with numbers:
import pandas as pd s = pd.read_csv("orders.csv") q1, q3 = s["amount"].quantile([0.25, 0.75]) upper = q3 + 1.5 * (q3 - q1) kept = s[s["amount"] <= upper] print("Rows:", len(s), "->", len(kept)) print("Mean:", round(s["amount"].mean(), 1), "->", round(kept["amount"].mean(), 1)) print("Electronics revenue:", round(s.loc[s["category"] == "Electronics", "amount"].sum()), "->", round(kept.loc[kept["category"] == "Electronics", "amount"].sum()))
OutputRows: 885 -> 812
Mean: 75.5 -> 52.1
Electronics revenue: 22850 -> 7124Deleting 73 real orders lowers the average basket from $75.5 to $52.1 and wipes out 68.8 percent of the Electronics revenue. Electronics suddenly looks like one of the smallest categories of the store. This is not cleaning; it is making the data look like the result you wanted.
You may also hear an objection: "Electronics is expensive anyway; let's give each category its own fence." This is a fairer view, and it flags 53 orders (in the Examples section). But the conclusion does not change: none of the flagged orders breaks the business rule, so none of them is an error.
Now a manager comes to you:
The manager says: "The average basket of $75.5 looks too high, remove the outliers." On the clean data the IQR rule flags 73 orders, and all of them follow the business rule. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
Sometimes you cannot know whether a value is an error or real. Then you do not delete it or correct it; you only mark it with a column: s["outlier"] = s["amount"] > upper. This column makes your decision visible, like the flag column in lesson 19. Then you run the analysis twice: with the flagged rows and without them. If the two results are close, the decision does not matter much; if they are very different, you write both in the report. This is called a sensitivity check: measuring how sensitive the result is to the decision you made. The "with/without" output in the Examples section shows this.
What happens if each category has its own Q1 and Q3? transform writes the quartile of its own category on every row (lesson 7).
import pandas as pd s = pd.read_csv("orders.csv") q1 = s.groupby("category")["amount"].transform("quantile", 0.25) q3 = s.groupby("category")["amount"].transform("quantile", 0.75) s["outlier"] = s["amount"] > q3 + 1.5 * (q3 - q1) print(s.groupby("category")["outlier"].sum()) print("Total:", s["outlier"].sum())
Outputcategory
Beauty 6
Books 1
Clothing 22
Electronics 15
Home & Living 9
Name: outlier, dtype: int64
Total: 53Electronics now gives 15 orders, not 42, because being expensive is normal in that category. Clothing moved to the front with 22. Still, all 53 orders follow the business rule: the number of alarms changed, the verdict did not.
On the same raw file, how many of the errors does the z > 3 rule catch?
import pandas as pd def price_to_number(text): text = text.replace(, ) text: text = text.replace(, ) (text) r = pd.read_csv().drop_duplicates() r = r[r[] != ] r[] = r[].map(price_to_number) r[] = r[].fillna((r[] / (r[] * (1 - r[]))).()) r[] = r[].() calculated = (r[] * r[] * (1 - r[])).(2) wrong = (r[] / calculated).(1) == 10 z = (r[] - r[].mean()) / r[].std() (, (z > 3).(), , (wrong & (z > 3)).()) (, (wrong & (z <= 3)).())
Deleting every value the IQR rule flags:
Outputs = s[s["amount"] <= upper] # 73 real orders disappearOn the clean copy this line deletes 73 real orders: the average basket drops from $75.5 to $52.1, and 68.8 percent of the Electronics revenue is lost. On the raw file it does the opposite: it throws away real expensive orders and leaves the two errors below the fence ($64.50 and $148.10) in the data. First correct the certain errors with the business rule; then keep the remaining extreme values or mark them.
Next lesson: The cleaning of the raw file is finished; you will join the steps of lessons 18–21 into one flow and take a first systematic look at the question "why did sales drop?".
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.
Outputz > 3: 12 | of these wrong: 6
Missed errors: 6The z rule flags 12 amounts; half of them are errors, and half are real Electronics orders. On top of that, it misses 6 errors. The IQR rule missed 2 errors, and the business rule missed none.
A sensitivity check with a flag column.
import pandas as pd s = pd.read_csv("orders.csv") q1, q3 = s["amount"].quantile([0.25, 0.75]) s["outlier"] = s["amount"] > q3 + 1.5 * (q3 - q1) print("With :", round(s["amount"].mean(), 1), "| median", s["amount"].median()) print("Without:", round(s.loc[~s["outlier"], "amount"].mean(), 1), "| median", s.loc[~s["outlier"], "amount"].median()) print("Flagged:", s["outlier"].sum(), "orders")
OutputWith : 75.5 | median 44.95
Without: 52.1 | median 40.46
Flagged: 73 ordersThe mean is very sensitive to the flagged orders (a $23.4 difference), and the median is less sensitive (a $4.5 difference). In a report you use the median for the typical basket and all orders for total revenue.