…
…
Statistics and Data Analysis Fundamentals · Lesson 22 / 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 lesson 10 you wrote a first answer to "What changed in May?" with a copy that someone else had cleaned. Now you start the same question the way an analyst really receives it: from the raw export of 902 rows. You will do the cleaning yourself, record every step, and finish with three hypotheses that are waiting to be tested.
This is a practice lesson: there is no new tool. In lessons 18–21 you found and fixed the problems of the raw file one by one: the quality report, missing-value decisions, duplicates, spelling differences, type conversion, and amount repair with a business rule. Each was a separate lesson, and each lesson had only that one step. In real work you do all of these steps in one file, in the right order, in one go, and you must be able to show another person what you did.
At the end of the lesson you will hand over two things. The first is a cleaning log: one line for each cleaning step, with the count before and after the step. The second is three hypothesis cards: each card has a hypothesis, the evidence that suggested it, the data that will test it, and the result that would weaken it. In between there is an exploratory look: in the clean data you will split the drop by period, device, category, and marketing data.
In this lesson you will:
Cleaning looks like a job you do once and forget: open the file, fix it, move on to the analysis. But two weeks later accounting asks, "Your report has 885 orders and the system has 902. Where are the other 17?" The answer must be in a record, not in your head. Without a log, cleaned numbers cannot be reproduced. Someone else reaches a different number from the same file, and people argue about which one is right.
Every line of the log says four things: which step, what you measured, the count before the step, and the count after the step. It is the same idea as the columns of the quality report in lesson 18: you name the problem with a number, then show that the number went to zero (or that you left it on purpose).
The order of the steps matters too. Duplicates and test orders come out first. If they stay, every later step counts them too and the numbers in the log are inflated. Spelling and date fixes can swap places with each other. But one chain is fixed: to calculate a missing quantity the unit price must be a number (you cannot divide by text), and to find amounts that are 10 times too large every row must have a quantity (an amount calculated from an empty quantity is empty too). So the order is: duplicates and tests, spelling, price, date, quantity, and amount last.
Put the cleaning lines in the right order. raw is the raw file, to_price is the function from lesson 20, and ten_x and expected come from the business rule.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now run all the steps in one cell. The code looks long, but you wrote each block alone in an earlier lesson. The only new thing is the log.append(...) line at the end of each block: you measure a number before the step (before), apply the step, measure the same number again, and add both to the log. The number you measure depends on the step: row count for duplicates, count of different values (nunique) for spelling, count of values that cannot become numbers for price, count of unreadable dates for date.
One spelling detail is new. The invisible character U+200B (a zero-width space) sits at the end of some values. You cannot see it on the screen, and strip() and lower() do not remove it, so "MOBILE" plus this character is not equal to "mobile". In Python you write it as the escape "\u200b", and str.replace("\u200b", "") removes it. The order of this step among strip() and lower() does not matter. The dictionary step that maps "desk top" to "desktop" comes last, after the text is clean, because the dictionary needs an exact match.
The last step is a decision step. In lesson 19 you saw two options for the empty delivery days of orders that are not canceled: leave them empty, or fill them with the median and add a flag. Here we are exploring and averages skip empty cells anyway, so we leave them and write the decision into the log as "before 54, after 54". A line that does not change is also information: the reader sees that you noticed the problem and left it on purpose. (In lesson 19 you saw that the medians by carrier were 2, 3, and 4 days. If you decided to fill, the carrier median would be a better choice than the overall median.)
Example 1 (case): Cleaning log and check
import pandas as pd raw = pd.read_csv("orders_raw.csv") log = [] # 1) Duplicates and tests before = len(raw) raw = raw.drop_duplicates() raw = raw[raw["customer_id"] != "TEST"] log.append(("duplicates and tests (rows)", before, len(raw))) # 2) Spelling: device and status for column, fix in [("device", {"desk top": "desktop"}), ("status", {"complete": "completed"})]: before = raw[column].nunique() raw[column] = raw[column].str.replace("\u200b", "").str.strip().str.lower().replace(fix) log.append((column + " (spellings)", before, raw[column].nunique())) # 3) Price: from text to number def to_price(text): text = text.replace(" USD", "") if "," in text: text = text.replace(",", ".") return float(text) before = pd.to_numeric(raw["unit_price"], errors="coerce").isna().() raw[] = raw[].map(to_price) log.((, before, raw[].isna().())) d = pd.to_datetime(raw[], format=, errors=) before = d.isna().() d = d.fillna(pd.to_datetime(raw[], format=, errors=)) raw[] = d.fillna(pd.to_datetime(raw[], format=, errors=)) log.((, before, raw[].isna().())) before = raw[].isna().() raw[] = raw[].fillna((raw[] / (raw[] * (1 - raw[]))).()) log.((, before, raw[].isna().())) before = (raw[] < 0).() raw[] = raw[].() log.((, before, (raw[] < 0).())) expected = raw[] * raw[] * (1 - raw[]) ten_x = (raw[] / expected).(1) == 10 before = ten_x.() raw.loc[ten_x, ] = (raw.loc[ten_x, ] / 10).(2) log.((, before, ((raw[] / expected).(1) == 10).())) empty = raw.loc[raw[] != , ].isna().() log.((, empty, empty)) (pd.DataFrame(log, columns=[, , ]).to_string(index=)) ((raw), (raw[].(), 2)) (raw[].value_counts().to_dict()) (raw.groupby(raw[].dt.month).size().tolist())
Output step before after
duplicates and tests (rows) 902 885
device (spellings) 8 2
status (spellings) 7 3
price (not a number) 111 0
date (unreadable) 172 0
quantity (empty) 23 0
quantity (negative) 2 0
amount (10x) 12 0
delivery (empty, not canceled) 54 54
885 66843.57
{'mobile': 516, 'desktop': 369}
[154, 177, 176, 162, 112, 104]The log table reads at a glance: 17 rows left (14 duplicates, 3 tests), eight different device spellings became two, seven status spellings became three; 111 text prices and 172 dates in other formats were converted; 23 empty quantities were calculated, 2 negative quantities were fixed, and 12 amounts had been written 10 times too large. to_string(index=False) prints the table without row numbers. In a log the numbers have no meaning, so it looks cleaner this way.
Some numbers in the log are smaller than the numbers in lesson 20: there the device spelling differed in 177 rows and the quantity was empty in 24 rows. The difference is normal. There we counted each problem in all 902 rows of the raw file, and here we count after the duplicate rows are gone. It is a small proof of why the log is kept in order.
The check is in the last three lines. How do you know the cleaning is right? If you have an independent source, you compare with it. Here you have one: the clean copy orders.csv that you used in lessons 4–17. It has 885 rows, a total revenue of $66,843.57, a device split of 516 mobile and 369 desktop, and monthly order counts of 154, 177, 176, 162, 112, 104. Your cleaning matched all four numbers to the cent. The only difference is in delivery days: in the clean copy those 54 cells are filled, and you left them empty on purpose because you have no carrier records. In real work there is often no clean copy. Then you check with business rules: every order should have exactly one row, revenue should agree with the accounting record, and the monthly counts should equal the counts in the order system.
What happens when the check does not match? By looking at which number does not match, you can guess where the mistake is.
In a friend's log the row count is 885, and the device split and the monthly counts are the same as in the clean copy, but the total revenue is exactly $58.05 higher than the clean copy. What is the most likely cause?
The data is clean and checked. Now it is time for the question: why did sales drop? This step is called exploratory data analysis. The statistician John Tukey made the term common in 1977 with a book of the same name. In Tukey's view statistics has two faces: exploration (looking in the data with an open mind to see what is there) and confirmation (testing one specific claim). In exploration you do not know exactly what you are looking for. You collect clues from tables and charts. The result is not a final answer but hypotheses that are worth testing.
In the next examples we read the clean copy (orders.csv) so the code stays short. The order counts and amounts are exactly the same as yours, as you just checked. In the exercises you will carry your own cleaning at the start of each step.
The first step of exploration is to clarify the question. What does "sales" mean: the number of orders, revenue, or amount per order (the basket)? In this lesson we count all orders (returns and cancellations included). In lesson 10 we counted only completed ones. The two definitions give different numbers, so you always write down which one you use. Then you make the comparison fair: January–April is four months and May–June is two months. Comparing the totals would compare two months with four months. You turn both periods into a monthly average.
months = pd.Series({"Jan-Apr": 4, "May-Jun": 2}) is a small series that holds the number of months in each period. summary["orders"].div(months) divides by matching the series to the period names: the "Jan-Apr" row by 4 and the "May-Jun" row by 2. The / [4, 2] in lesson 10 divided by position from a list. Matching by name makes sure each row is divided by the right number even if the order of the rows changes.
Example 2 (case): Orders, revenue, or basket?
import pandas as pd orders = pd.read_csv("orders.csv") orders["date"] = pd.to_datetime(orders["date"]) orders["period"] = "Jan-Apr" orders.loc[orders["date"] >= "2026-05-01", "period"] = "May-Jun" months = pd.Series({"Jan-Apr": 4, "May-Jun": 2}) summary = orders.groupby("period").agg(orders=("order_id", "count"), revenue=("amount", "sum"), median_basket=("amount", "median")) summary = summary.loc[["Jan-Apr", "May-Jun"]] summary["orders"] = summary["orders"].div(months) summary["revenue"] = summary["revenue"].div(months) print(summary.round(1)) print(((summary.loc["May-Jun"] / summary.loc["Jan-Apr"] - 1) * 100).round(1))
Output orders revenue median_basket
period
Jan-Apr 167.2 13034.0 45.0
May-Jun 108.0 7353.8 44.8
orders -35.4
revenue -43.6
median_basket -0.2
dtype: float64Monthly orders fell from 167.25 to 108 (the table shows 167.2 because an exact half rounds to the even digit): 35.4 percent. Monthly revenue fell from $13,034 to $7,354, which is 43.6 percent. The median basket went from $44.95 to $44.85, almost no change. The baskets have the same size, but fewer orders arrive. This first finding changes the direction of the question. You should not ask "why do customers spend less?" but "why do fewer customers place orders?"
Next is the "where?" question. The cell below turns the period × device table into monthly averages and prints the percent change. Here periods are in the rows and devices are in the columns, and div(..., axis=0) divides each row by the number that belongs to its own period name.
Try it now· not graded; doesn't affect progress
Run it: monthly orders on mobile went from 101.8 to 54.5 (46.4 percent), and on desktop from 65.5 to 53.5 (18.3 percent). Then write category in place of device in two places and run it again. Which category fell hardest, and which fell least?
Let's look at the category table in sorted form and add a crosstab next to it: how are the orders of each device spread over the categories? normalize="index" from lesson 8 turns each row into shares of its own total, so each row adds up to 1.
Example 3 (case): Category drop and device × category shares
import pandas as pd orders = pd.read_csv("orders.csv") orders["date"] = pd.to_datetime(orders["date"]) orders["period"] = "Jan-Apr" orders.loc[orders["date"] >= "2026-05-01", "period"] = "May-Jun" tab = orders.groupby(["period", "category"]).size().unstack() tab = tab.div(pd.Series({"Jan-Apr": 4, "May-Jun": 2}), axis=0) print(((tab.loc["May-Jun"] / tab.loc["Jan-Apr"] - 1) * 100).round(1).sort_values()) print(pd.crosstab(orders["device"], orders["category"], normalize="index").round(3))
Outputcategory
Clothing -44.2
Electronics -37.8
Beauty -37.1
Home & Living -26.3
Books -24.7
dtype: float64
category Beauty Books Clothing Electronics Home & Living
device
desktop 0.111 0.119 0.141 0.295 0.333
mobile 0.188 0.141 0.415 0.091 0.165The hardest drop is in Clothing: 44.2 percent. The first thought is "there is a problem with clothing products." But look at the crosstab: 41.5 percent of mobile orders are Clothing, while on desktop the share is only 14.1 percent. If mobile orders fell 46 percent, the category that has a large weight on mobile will naturally fall hard too. The drop in Clothing may not come from a problem of its own. It may come from carrying the drop of mobile.
In exploration you write the first explanation that comes to mind next to each finding. The candidate is not an explanation yet. It is a suspect that you will test in the next step. And some candidates fall as soon as you look at the data.
Match each finding with the first explanation candidate that comes to mind.
For each row, pick its match from the list, then check.
The orders table shows only the people who ordered. The people who came to the store and left without buying are not there. For them you need outside data: marketing.csv has ad spend, number of visitors, and number of orders for each day. From it you calculate the conversion rate: orders / visitors × 100, which is how many of every hundred visitors placed an order. Did revenue fall because fewer visitors came, or because fewer of the visitors bought? The two lead to different hypotheses: the first to ads and traffic, the second to the store itself (page, price, checkout).
There is a subtle point when you calculate conversion. The conversion of a month is the total orders of that month divided by the total visitors, not the average of the daily rates. This way a busy day and a quiet day do not count with the same weight. It is the same idea as the weighted mean in lesson 13. We also count how many new customers signed up each month from the customers table.
Example 4 (case): Ads, visitors, conversion, and new customers
import pandas as pd mkt = pd.read_csv("marketing.csv") mkt["date"] = pd.to_datetime(mkt["date"]) g = mkt.groupby(mkt["date"].dt.month).agg(ads=("ad_spend", "mean"), visitors=("visitors", "mean"), orders=("orders", "sum"), total_visitors=("visitors", "sum")) g["conversion"] = (g["orders"] / g["total_visitors"] * 100).round(3) cust = pd.read_csv("customers.csv") cust["signup_date"] = pd.to_datetime(cust["signup_date"]) new = cust[cust["signup_date"] >= "2026-01-01"] g["new_customers"] = new.groupby(new["signup_date"].dt.month).size() print(g[["ads", "visitors", "conversion", "new_customers"]].round({"ads": 0, "visitors": 0}))
Output ads visitors conversion new_customers
date
1 227.0 1544.0 0.322 105
2 226.0 1575.0 0.401 89
3 217.0 1544.0 0.368 119
4 228.0 1553.0 0.348 90
5 26.0 1266.0 0.285 36
6 23.0 1262.0 0.275 23Four things changed at the same time. Average daily ad spend went from a band of $217–$228 down to $26 in May and $23 in June. Daily visitors went from about 1,550 down to about 1,265 (roughly 18 percent). Conversion went from a band of 0.32–0.40 percent down to 0.285 and 0.275 percent. New customer sign-ups were 119 in March and 90 in April, but 36 in May and 23 in June. So fewer people came, and fewer of those who came bought something. Traffic is not the only source of the drop. If traffic alone had changed, conversion would have stayed the same.
In this table we used daily averages because the months have different lengths (February has 28 days, March has 31). The same trap is bigger in the period comparison: what happens when you compare totals of four months and two months? The code below puts the two definitions side by side with the monthly order counts.
Change the period definition: how big does the drop look?
Pick a value; predict the output first, then look.
1period_definition = "total"2monthly = [154, 177, 176, 162, 112, 104]3before = sum(monthly[:4])4after = sum(monthly[4:])5if period_definition == "monthly average":6 before = before / 47 after = after / 28print(period_definition, before, "→", after, "| %", round((after / before - 1) * 100, 1))
total 669 → 216 | % -67.7
Faded lines didn't run with this value. With totals the drop looks like 67.7 percent, but that compares two months with four months. With monthly averages the real drop is 35.4 percent. When you compare periods of different length, always convert to an average per unit (month, day) and write it in the report: "monthly average orders".
So far you have produced dozens of numbers. In exploration this is normal: you try many cuts, most say nothing, and a few catch your eye. The danger is here too. If you try enough cuts and charts, you will always find something that looks interesting by chance. If you look at forty different splits, one of them can show a big difference even when there is no real difference at all. So you cannot call a pattern "proven" with the same data in which you found it. Exploration produces hypotheses. Confirmation is a separate step, and it is done either with new data or with a method that measures the role of chance (you will learn this in units 5 and 6).
You found an interesting pattern in an exploratory analysis. Can you call it "proven" with the same data?
In exploration it helps to see many charts side by side, because the eye scans the distribution, the time, and the relationship at once. fig, axes = plt.subplots(2, 2, figsize=(10, 7)) makes a grid of four axes. axes works like a two-dimensional array: top left is axes[0, 0] and bottom right is axes[1, 1]. For a grid with one row (plt.subplots(1, 2)), axes[0] and axes[1] are enough. figsize gives the width and height in inches, and fig.tight_layout() stops the titles from overlapping. The rule of lesson 17 holds on a dashboard too: the title of each chart says what it shows.
Example 5 (case): A four-chart exploration dashboard
import pandas as pd import matplotlib.pyplot as plt orders = pd.read_csv("orders.csv") orders["date"] = pd.to_datetime(orders["date"]) mkt = pd.read_csv("marketing.csv") fig, axes = plt.subplots(2, 2, figsize=(10, 7)) axes[0, 0].hist(orders["amount"], bins=30) axes[0, 0].set_title("Amounts are right-skewed: more than half are under $50") monthly = orders.groupby(orders["date"].dt.month).size() axes[0, 1].plot(monthly.index, monthly.values, marker="o") axes[0, 1].set_title("Monthly orders fell from 162 to 112 in May") counts = orders["category"].value_counts().sort_values() axes[1, 0].barh(counts.index, counts.values) axes[1, 0].set_title("Clothing has the most orders") axes[1, 1].scatter(mkt["ad_spend"], mkt["visitors"], alpha=0.5) axes[1, 1].set_title("As ad spend rises, visitors rise") fig.tight_layout() print(axes.shape) print(monthly.tolist()) print(counts.idxmax(), counts.max())
Output(2, 2)
[154, 177, 176, 162, 112, 104]
Clothing 266axes.shape shows that the grid has 2 rows and 2 columns. Look at the bottom right corner of the dashboard: on days with high ad spend, visitors are high too. This is a relationship, but it is not enough to say "ads bring visitors." Maybe on weekends both the ads are increased and people browse more. Remember lesson 3: in observational data, moving together does not show that one causes the other. That is why the title says "rise" and not "bring".
The last step of exploration is to turn findings into hypotheses. A weak hypothesis sounds right, but no data can prove it wrong. A testable hypothesis answers three questions: which data will be used, which comparison will be made, and which result would weaken the hypothesis. The third is the one that is forgotten most often: the value of a hypothesis comes from saying in advance what would disprove it.
First try it in another context. The weekly visitor count of a city library dropped clearly in the second half of June. You have the weekly entry counts, the opening hours, and the school calendar. Schools closed on June 20.
Example 6 (outside the case): Weekly entries of the library
import pandas as pd lib = pd.DataFrame({ "week": [1, 2, 3, 4, 5, 6, 7, 8], "visits": [1290, 1320, 1290, 1320, 780, 750, 780, 750], }) lib["period"] = "school open" lib.loc[lib["week"] >= 5, "period"] = "school closed" avg = lib.groupby("period")["visits"].mean().loc[["school open", "school closed"]] print(avg) print(round((avg["school closed"] / avg["school open"] - 1) * 100, 1))
Outputperiod
school open 1305.0
school closed 765.0
Name: visits, dtype: float64
-41.4The weekly average of entries went from 1,305 to 765: 41.4 percent. The first sentence that comes to mind is "People don't read books anymore." This is a weak hypothesis: it does not say which data to look at, what to compare with, or which result would disprove it. The testable version is: "Schools closed on June 20. If the drop is clearly larger in entries made with a student card than in adult entries, this explanation is supported. If both entry types fell by about the same rate, the school calendar explanation is weakened." If the entry records of the library have a card type, you can test this hypothesis with one table. You will do this yourself at the end of the exercises.
Now go back to Bazaar. Which of the three hypothesis cards below is testable?
Your teammate prepared a draft of three hypothesis cards. Which one do you put on the testing list?
Pick an option and see what happens. There are no points; you can try the other options too.
Collect what you found in exploration on three cards. Each card should propose a different mechanism. Writing the same idea three times makes the list longer but gives no more information.
| Card | Hypothesis | Evidence (from exploration) | Test data | Which result weakens it | Where it will be tested |
|---|---|---|---|---|---|
| H1 | Cutting the ads may have reduced traffic | Daily ads $224.49 → $24.55; daily visitors 1,553 → 1,264 | marketing.csv: ad_spend, visitors | If there is no relationship between ads and visitors on weekdays either | Lessons 36–38 (scatter, correlation, regression) |
| H2 | The new mobile checkout page may have lowered mobile conversion | Monthly mobile orders fell 46 percent, desktop 18 percent | sessions.csv: group, purchased (the A/B test in April) | If the purchase rate of group B is no different from group A | Lesson 29 (permutation test), lesson 34 (chi-square) |
| H3 | The Electronics price increase may have reduced Electronics orders | Since May the unit price is 1.12 times the list price; Electronics fell 37.8 percent |
Look at the language of the cards: all of them say "may". None says "this is the reason", because exploration cannot show that. The last column of each card is also the most important one: writing the result that would disprove the hypothesis in advance stops you from fooling yourself when you look at the data later.
In this unit you did the unseen half of an analyst's work. You got to know the raw file (18), decided about the missing values (19), fixed duplicates, spellings, and types (20), found the wrong amounts with a business rule (21), and in this lesson you ran all of it in the right order, recorded and checked. Then you split the drop in the clean data and left three hypotheses.
You have three hypotheses, but all of them are at the level of "may". Mobile fell 46 percent and desktop fell 18 percent. Is this a real difference, or is it a game of chance? To say that, you first need to learn to measure chance. Unit 5 will do exactly this.
Test the "delivery time got longer" candidate from the matching block with data. Look at the monthly average delivery days. Canceled orders have empty delivery days, so they do not enter the average.
import pandas as pd orders = pd.read_csv("orders.csv") orders["date"] = pd.to_datetime(orders["date"]) print(orders.groupby(orders["date"].dt.month)["delivery_days"].mean().round(2))
Outputdate
1 2.84
2 2.97
3 2.95
4 3.16
5 2.96
6 3.00
Name: delivery_days, dtype: float64Over six months delivery time stays between 2.84 and 3.16 days. May and June are inside the range of the first four months. This candidate leaves the list. In exploration, removing a candidate is also a finding, and it goes into the log.
Evidence for card H3: bring the list price from the product table to the orders, then average the ratio of unit price to list price by category and period.
import pandas as pd orders = pd.read_csv("orders.csv") products = pd.read_csv("products.csv") orders["period"] = "Jan-Apr" orders.loc[orders["date"] >= "2026-05-01", "period"] = "May-Jun" merged = orders.merge(products[["product_id", ]], on=, how=, validate=) merged[] = merged[] / merged[] tab = merged.groupby([, ])[].mean().unstack() (tab[[, ]].(2))
Comparing the totals of periods with different lengths. There are 669 orders in January–April and 216 in May–June. Saying "a 68 percent drop" is wrong, because the first period is four months and the second is two. After you convert to monthly averages, the drop is from 167.25 to 108, which is 35.4 percent. The same mistake is made with ad spend, visitors, and revenue. The right way: divide the totals by the number of months or days (or take the average of the daily records directly) and write "monthly average" or "daily average" in the report.
Next lesson: Mobile fell 46 percent and desktop fell 18 percent. Is this gap bigger than chance? First we will learn to measure chance: probability and simulation.
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.
orders.csv + products.csv: drop of Electronics against other categories, by device |
| If Electronics does not fall harder than the other categories on desktop |
| Lesson 37 (confounders and comparison) |
Outputperiod Jan-Apr May-Jun
category
Beauty 1.0 1.00
Books 1.0 1.00
Clothing 1.0 1.00
Electronics 1.0 1.12
Home & Living 1.0 1.00Only in Electronics, and only after May, the unit price is 1.12 times the list price. The price increase is real and belongs to one category only. That is why H3 deserves to be a card of its own. In this example the date stayed as text. Comparing text in year-month-day format works the same as calendar order.