…
…
Statistics and Data Analysis Fundamentals · Lesson 20 / 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.
Most of the problems in the quality report are about consistency. The same order was saved twice, three test orders slipped in, the device is written in eight ways and the status in seven, 113 prices were typed as text like "164,95 USD", and the dates come in three different formats. In this lesson you fix them in order, check every step with a number, and bring the raw file down to the same 885 rows as the clean copy.
At the end of the lesson you will be able to clean the raw file step by step, as in this table:
OutputStep Before After
Exact duplicates 902 rows 888 rows
Test orders 888 rows 885 rows
Device spellings 8 different values 2 values (mobile, desktop)
Status spellings 7 different values 3 values (completed, returned, canceled)
Unit price text ("72,75 USD") number (float64)
Date text, three formats date (datetime64), 0 missing
Check: monthly order counts [154, 177, 176, 162, 112, 104], same as the clean copyIn this lesson you will:
value_counts after every step.In lesson 18 you ran a quality scan on the raw order file and made a list: 14 exact duplicates, orders with the customer id TEST, 8 different spellings in the device column and 7 in the status column, some prices stored as text, and dates in three formats. In lesson 19 you dealt with missing values. In this lesson you close the rest of the list.
Consistency problems usually come from data that arrives from several sources, from different screens, or from typing by hand. The mobile app writes "mobile", the old web panel writes "Mobile", and an employee pastes "MOBILE" from a web page and brings an invisible character along. The accounting screen saves a price as "164,95 USD" and the store screen saves it as "164.95". Each source is consistent on its own. The problem starts when they all meet in one table. A computer does not know that "mobile" and "Mobile" mean the same thing: when you count, you get two groups, and when you add up, you get two rows.
The way to fix this is to treat each problem as a separate step and count the result after every step. Write the step, run it, count. If you do not get the number you expected, do not go to the next step. Every step in this lesson follows this rhythm.
A duplicate is the same event appearing in a table in more than one row. The simplest kind is an exact duplicate: two rows with every column identical. It usually comes from an import that ran twice or a button that was pressed twice. If you do not delete it, that order is counted twice and its revenue is added twice.
In lesson 18 you counted 14 exact duplicates with h.duplicated().sum(). For each row, duplicated() answers the question "is this row the same as an earlier row?": the first row seen is False, and its later copies are True. If you want to see the duplicates before deleting, write keep=False. Then every copy in a group is True, and you can see the duplicate rows side by side.
To delete, you use drop_duplicates(). By default it keeps only the first of the rows whose columns are all the same and deletes the copies. Duplicates are not always exact: the same order may have been imported again at another time, and one column may have been updated in between. Then you look for the duplicate by a key. A key is a column that identifies each event by itself; in the orders it is order_id. drop_duplicates(subset="order_id") looks only at this column. keep says which copy stays: keep="first" (the default) keeps the first one, keep="last" keeps the last one.
A relative of the duplicate is the record outside the analysis: a row that is not real customer behavior. Test orders that developers place to try the system, or tries that staff make with their own account, are like this. The raw file has three orders with the customer id TEST. You remove them with a condition, the filter from lesson 5: h[h["customer_id"] != "TEST"].
Example 1 (case): duplicates and test orders. Let's first see the duplicate rows side by side, then delete them:
import pandas as pd h = pd.read_csv("orders_raw.csv") print(len(h), h.duplicated().sum()) pairs = h[h.duplicated(keep=False)].sort_values("order_id") print(len(pairs)) print(pairs[["order_id", "date", "customer_id", "amount"]].head(4)) h = h.drop_duplicates() print(len(h), h["order_id"].nunique()) print((h["customer_id"] == "TEST").sum()) h = h[h["customer_id"] != "TEST"] print(len(h))
Output902 14
28
order_id date customer_id amount
429 S00029 06.01.2026 M0038 21.45
776 S00029 06.01.2026 M0038 21.45
658 S00043 08.01.2026 M0131 29.96
676 S00043 08.01.2026 M0131 29.96
888 888
3
885The 14 duplicates show up as 28 rows with keep=False: 14 pairs. After sorting, you can see that the copies sit side by side and are really the same. After drop_duplicates() there are 888 rows and 888 different order ids: every id is now in exactly one row. So at Bazaar all the key duplicates were exact duplicates; if you had deleted with subset="order_id", you would still have 888. Then the three test orders go, and 885 rows remain.
Does the order of the two steps matter? Not here, but the general rule is "look first, then delete". If the same id appears in two rows and the rows are different, you must decide which one is right; code cannot make that decision for you.
The same order_id appears in two rows: one has status "returned", the other "completed", and every other column is the same. What does h.drop_duplicates() do to these two rows?
Let's see the decision about duplicates in another table. Example 2 (outside the case): a six-row member list of a gym. Maya Reed is registered twice: after her first registration she changed her email address and filled in the form again. The city column is also written in mixed ways. The names and emails are fictional.
import pandas as pd members = pd.DataFrame({ "name": ["Maya Reed", "Marco Hill", "Maya Reed", "Lena Park", "Noah Shaw", "Zara Quinn"], "email": ["maya.reed@example.com", "marco.hill@example.com", "mayareed@newmail.example.com", "lena.park@example.com", "noah.shaw@example.com", "zara.quinn@example.com"], "city": ["Port Alder", "port alder ", "PORT ALDER\u200b", "Kingsbridge", "Port Alder", "Kingsbridge"], "joined": ["2026-01-10", "2026-02-03", "2026-05-21", "2026-03-14", "2026-04-02", "2026-04-18"], }) print(members.duplicated().sum()) print(members.duplicated(subset="name").sum()) print(members[members.duplicated(subset="name", keep=False)])
Output0
1
name email city joined
0 Maya Reed maya.reed@example.com Port Alder 2026-01-10
2 Maya Reed mayareed@newmail.example.com PORT ALDER 2026-05-21There are zero exact duplicates: Maya's two rows are not identical. When you look by name, one duplicate appears. Which row should stay? The answer is not in the code; it is in the job. It depends on what the gym wants to do:
The gym will send a campaign email to its members. Maya Reed is in two rows; her emails are different, and her registration dates are January 10 and May 21. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
This is the main idea of the lesson: keep is not only a parameter, it is a decision. In real tables, using "name" as a key is also risky (there may be two different people called Maya Reed); if the gym has a real key such as a member number, you use that. We will come back to the city column in a moment.
Now let's move to the device column. The scan in lesson 18 found 8 different spellings: mobile, Mobile, mobile (space at the end), MOBILE followed by a hidden character, desktop, Desktop, desktop (space at the start), and desk top. In reality there are only two devices. Reducing a category to one form is called a spelling standard. You do it with a chain of four steps:
1. Delete the spaces: str.strip() removes the spaces at the start and the end.
2. Delete the hidden character: str.replace("\u200b", "").
3. Make lowercase: str.lower().
4. Match what is left with a dictionary: replace({"desk top": "desktop"}).
You know the first and third steps from lesson 6. The replace in the fourth step is a little different: .str.replace("a", "b") changes a part inside each string, while .replace({...}) (no .str in front) changes the whole value according to the dictionary. The dictionary key is the old value and its match is the new value; values that are not in the dictionary stay as they are. It turns the value "desk top" into "desktop", but it does not touch another string that only contains "desk top".
Why is the second step needed? Some of the values were copied and pasted from a web page, and they carry a zero-width space (Unicode U+200B). It takes no space on the screen, so MOBILE with this character looks exactly like MOBILE without it. But it is a real character. strip() removes only spaces, tabs, and line breaks, so it stays. lower() changes only letters, so it stays too. The string is one character longer, and it is not equal to the clean one.
What does the expression "MOBILE\u200b".lower() == "mobile" give? (\u200b is the hidden zero-width space.)
Example 3 (case): the device column. First with only strip and lower, then with the full chain:
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h["device"].nunique()) half = h["device"].str.strip().str.lower() print(half.value_counts()) full = h["device"].str.strip().str.replace("\u200b", "").str.lower().replace({"desk top": "desktop"}) print(full.value_counts())
Output8
device
mobile 508
desktop 357
mobile 20
desk top 17
Name: count, dtype: int64
device
mobile 528
desktop 374
Name: count, dtype: int64The half chain brings 8 values down to 4, but two problems are left. The 20 rows of mobile followed by the hidden character come from the invisible trap: on the screen they look like "mobile", but value_counts counts them separately. The 17 rows of desk top are a spelling difference: lowercase cannot fix it, but a dictionary can. The full chain leaves two values: mobile 528, desktop 374. The total is 902; no row was lost, only the names were joined. (The duplicates and test orders are not removed yet, so the total is 902.)
Now apply the same chain to the status column yourself. The status has seven spellings (completed, Completed, complete, returned, Returned followed by a hidden character, canceled, Canceled followed by a hidden character); the goal is three values.
Try it now· not graded; doesn't affect progress
Returned and Canceled carry the hidden character, so the second step is needed here too. You need to put {"complete": "completed"} in the dictionary: no change of letters fixes a different word form on its own.
The steps of the chain cannot be written in any order. The dictionary comes last: its keys are written in lowercase and without spaces, so the matching works correctly only after the values are cleaned. Before that, lower() must already be done, or Mobile would not match a lowercase key. In this file the first three steps can swap places: strip, removing the hidden character, and lower do not depend on each other.
The city column of the gym list in Example 2 shows why the hidden-character step matters: "Port Alder", "port alder ", "PORT ALDER" with a hidden character, "Kingsbridge".
import pandas as pd city = pd.Series(["Port Alder", "port alder ", "PORT ALDER\u200b", "Kingsbridge", "Port Alder", "Kingsbridge"]) print(city.str.strip().str.lower().value_counts()) print(city.str.strip().str.replace("\u200b", "").str.lower().value_counts())
Outputport alder 3
kingsbridge 2
port alder 1
Name: count, dtype: int64
port alder 4
kingsbridge 2
Name: count, dtype: int64Without the hidden-character step, three different values remain: three spellings became port alder, and the one that was typed with the hidden character stays as its own value that looks the same. With the step there are two values: 4 members in Port Alder and 2 in Kingsbridge. If you had prepared a report by city, the first version would have shown Port Alder as two different cities.
Put the lines that reduce the device column to two values in the order of the four-step chain from the lesson (strip, hidden character, lowercase, dictionary).
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Next is type conversion. A conversion changes the format and keeps the information: "164,95 USD" and 164.95 are the same price, but the first one is a string, and you cannot add it, average it, or multiply it. In lesson 18 you saw in the dtypes output that the unit_price column is a string (str), not a number. If even one value in a column is a string, pandas reads the whole column as strings.
The pandas tool that converts strings to numbers is pd.to_numeric. Let's try directly:
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h["unit_price"].dtype) print(h["unit_price"].iloc[[0, 12]].tolist()) print(h["unit_price"].str.contains(" USD", regex=False).sum())
Outputstr
['72.75', '164,95 USD']
113If you write pd.to_numeric(h["unit_price"]), the code raises an error, and the error message shows the first value that could not be converted: "164,95 USD". Reading the message is very useful here; it tells you the problem directly. There are two formats:
72.75: the decimal point is the decimal separator (the format of the software world).164,95 USD: the comma is the decimal separator, with " USD" at the end (the format of an accounting export). 113 rows are like this.The rule is: first delete " USD"; if there is a comma in the string, it is a decimal comma, so change it to a decimal point; if there is no comma, do not touch it; then convert to a number with float. The word "if" means an if. Let's write it with a function you know from the Python course:
Example 4 (case): the price conversion function.
import pandas as pd def convert_price(text): text = text.replace(" USD", "") if "," in text: text = text.replace(",", ".") return float(text) print(convert_price("72,75 USD"), convert_price("72.75"), convert_price("19,95 USD")) h = pd.read_csv("orders_raw.csv") h["unit_price"] = h["unit_price"].map(convert_price) print(h["unit_price"].dtype, h["unit_price"].min(), h["unit_price"].max(), h["unit_price"].isna().sum())
Output72.75 72.75 19.95
float64 1.0 449.95 0The function takes one string and returns one number. To apply it to a whole column you use map: series.map(function) applies the function to every value in the column, one by one, and builds a new column from the results. (You write the name of the function without parentheses: map(convert_price); you are not the one calling it, map is.) The result is float64: the smallest price is $1.00, the largest is $449.95, and there is no value that could not be converted. A smallest price of $1.00 looks strange; we will look at values that are "too small or too big" in lesson 21. For now we only fixed the format.
A shortcut may come to mind: "Delete every comma." In English-style numbers the comma separates thousands, as in 1,234.50, so this guess is natural. In this file it is wrong: 72,75 becomes 7275. The code does not raise an error; the numbers just become 100 times bigger. If you did this on the raw file, the largest price would be $44,995.00 instead of $449.95, and 164,95 USD would become 16495.0. Try the two rules side by side with different inputs:
For which inputs do the two rules give different results?
Pick a value; predict the output first, then look.
1text = "72,75 USD"23def correct_rule(t):4 t = t.replace(" USD", "")5 if "," in t:6 t = t.replace(",", ".")7 return float(t)89def delete_commas(t):10 t = t.replace(" USD", "").replace(",", "")11 return float(t)1213print("Correct rule:", correct_rule(text))14print("Delete every comma:", delete_commas(text))
Correct rule: 72.75 Delete every comma: 7275.0
Faded lines didn't run with this value. For the values with a comma ("72,75 USD" and "19,95 USD") the rules differ: deleting every comma turns them into 7275.0 and 1995.0, 100 times too big. For the values with a decimal point ("72.75", "449.95", "9.45") both rules agree. Because the code raises no error, this mistake is noticed only when you check a result, such as the largest price.
The date column is also text, written in three formats: 2026-06-17 (year-month-day), 08.03.2026 (day.month.year), and 3/8/2026 (month/day/year, with no leading zeros). In lesson 6 you converted strings to dates with pd.to_datetime(df["date"]); there all the dates had the same format. Here you must tell pd.to_datetime the format yourself.
You write the format in the format parameter as a pattern: %Y is the four-digit year, %m the month, %d the day; the characters between them (hyphen, period, slash) are written as they are. "%Y-%m-%d" reads "2026-06-17", and "%d.%m.%Y" reads "08.03.2026". If a value does not fit the pattern, pd.to_datetime normally raises an error. If you write errors="coerce", it turns that value into NaT (Not a Time: the NaN of dates) instead of raising an error. isna().sum() and fillna, which you know from lesson 19, work for NaT too.
The method: first convert with the first format and count the NaT that remain; then fill the NaT with the result of the second format, and count again; then the third.
Example 5 (case): three date formats.
import pandas as pd h = pd.read_csv("orders_raw.csv") print(h["date"].iloc[[0, 5, 9]].tolist()) t = pd.to_datetime(h["date"], format="%Y-%m-%d", errors="coerce") print(t.isna().sum()) t = t.fillna(pd.to_datetime(h["date"], format="%d.%m.%Y", errors="coerce")) print(t.isna().sum()) t = t.fillna(pd.to_datetime(h["date"], format="%m/%d/%Y", errors="coerce")) print(t.isna().sum(), t.min().date(), t.max().date()) print(t.dt.month.value_counts().sort_index().tolist())
Output['2026-06-17', '3/8/2026', '2026-01-21']
179
62
0 2026-01-01 2026-06-30
[159, 184, 177, 165, 112, 105]After the first format, 179 dates are left as NaT (in the scan of lesson 18 you found "179 rows without a hyphen"). The dotted format reads 117 of them, and 62 remain; the slash format reads the remaining 62, and the NaT count goes down to zero. The smallest date is January 1 and the largest is June 30: Bazaar's six-month period. The month counts are 159, 184, 177, 165, 112, 105; they are a little higher than in the clean copy because the duplicates and test orders are not removed yet.
There seems to be a shorter way: pd.to_datetime(h["date"], format="mixed", dayfirst=True). format="mixed" tells it to guess the format of each value separately, and dayfirst=True tells it to read the day first when it is unclear. It is one line, and it raises no error. But a guess is a guess:
Which date does pd.to_datetime("2026-03-08", format="mixed", dayfirst=True) give?
On the raw file, this "easy way" converts 302 dates wrongly, and orders from July to December appear in the month counts, although Bazaar's data ends in June. If you write only format="mixed" (without dayfirst), this time it reads dates like 08.03.2026 month first and breaks 45 dates. There is no error message in either case. The rule is simple: if you know the format, say it, then check the NaT count and the smallest and largest dates. Try the three-step conversion yourself:
Try it now· not graded; doesn't affect progress
When the cleaning is finished, the strongest check is to compare the result with an independent source. In this course you have a clean copy (orders.csv). When you apply all the steps in order (duplicates, test orders, device, status, price, date), the result is:
OutputRow count 885 (clean copy: 885)
Device mobile 516, desktop 369
Status completed 787, returned 64, canceled 34
Monthly order counts [154, 177, 176, 162, 112, 104] (clean copy: same)The device and status counts are a little smaller than in Example 3, because the duplicates and test orders are gone now. The monthly counts matching the clean copy exactly shows that the date conversion and the row removal were done correctly. But be careful: this equality checks only the counts. It does not tell you whether the amounts are right, for example whether a price of $1.00 is real; that question is the job of lesson 21.
In real work there is no clean copy. Instead you check business rules: every order should have exactly one row (is the row count equal to nunique?), the device can take only two values, the dates should be inside the data period, and the total revenue should agree with the accounting records. Each rule turns into a number, and each number becomes a check line.
In lesson 19 you found 24 missing quantities and said they were calculable missing values: the amount, the unit price, and the discount are filled in, so quantity = amount / (unit price × (1 − discount)). You could not apply it that day, because the unit price was a string. Now it is a number.
Example 6 (case): calculate the missing quantities. In the order of lesson 19: first the flag column, then the calculation, then filling, then the number still missing.
import pandas as pd def convert_price(text): text = text.replace(" USD", "") if "," in text: text = text.replace(",", ".") return float(text) h = pd.read_csv("orders_raw.csv") h["unit_price"] = h["unit_price"].map(convert_price) h["quantity_missing"] = h["quantity"].isna() calc = (h["amount"] / (h["unit_price"] * (1 - h["discount"]))).round() h["quantity"] = h["quantity"].fillna(calc) print(h.loc[h["quantity_missing"], "quantity"].value_counts()) print(h["quantity"].isna().sum(), h["quantity_missing"].sum())
Outputquantity
1.0 15
2.0 8
3.0 1
Name: count, dtype: int64
0 24All 24 missing quantities were filled: 1 item in 15 orders, 2 items in 8 orders, and 3 items in one. The number still missing is 0; the flag column remembers that 24 rows were filled. Why did we add round() to the calculation? The division is done with floating point numbers, and in one row the result can come out as 0.9999999999999999 instead of 1; because quantity is a whole count, you round it. This is a calculation, not an estimate: if the amount, the price, and the discount are right, the quantity is exactly right. The "if they are right" part is important; in lesson 21 you will see that some amounts are wrong. Write the formula yourself:
Try it now· not graded; doesn't affect progress
In a school's grade file, the grades were typed as strings: "85", "85,5", "eighty", "92", "70". We write errors="coerce" so that pd.to_numeric does not raise an error and makes the values it cannot convert NaN; then we immediately look at how many values could not be converted and which ones they are:
import pandas as pd grades = pd.Series(["85", "85,5", "eighty", "92", "70"]) n = pd.to_numeric(grades, errors="coerce") print(n.tolist()) print(n.isna().sum()) print(grades[n.isna()].tolist())
Output[85.0, nan, nan, 92.0, 70.0]
2
['85,5', 'eighty']Two values could not be converted. "eighty" is an expected problem, but "85,5" is a surprise: to_numeric does not accept a comma as the decimal separator. errors="coerce" silences the error and erases the information, so looking at the NaN count afterwards is a must. The right work here is to save "85,5" by changing the comma to a decimal point, as in the price, and to fix "eighty" by hand or leave it missing and flag it. If you leave the NaN that coerce made without looking, you lose the grades of two students.
Let's apply the good option in the gym list of Example 2: sort by registration date and keep the latest record for each name.
Missing a hidden character. str.lower() and strip() do not remove it. "MOBILE\u200b".lower() does not give "mobile"; it gives a value that looks the same on the screen but is different:
Output"MOBILE\u200b".lower() → 'mobile\u200b' (7 characters)
"MOBILE\u200b".lower() == "mobile" → FalseIn a grouping, this value comes out as a separate row: at Bazaar, 20 mobile orders would look like a "device" of their own. Write str.replace("\u200b", "") before you count, and check the result with value_counts(). If the number of values is not what you expected, look for two rows that look the same; most likely one of them has a hidden character. print(repr(value)) shows it: 'mobile\u200b' instead of 'mobile'. (The hidden character is only one case: spaces at the start or end are another, and strip() handles them.)
duplicated(keep=False), then delete them with drop_duplicates(); in a key duplicate, which row stays (subset, keep) is a business decision. Records outside the analysis, such as test and staff records, are removed with a condition.strip, replace("\u200b", ""), lower, then a dictionary with replace({...}); count with value_counts after every step.map for prices, format=... and errors="coerce" for dates), count what could not be converted, and check the result with an independent source or a business rule; code that raises no error is not necessarily right.Next lesson: The data is now consistent and has the right types. What remains are values that "look too big or too small": the $1.00 price, the amounts that are ten times too large. In lesson 21 you will find outliers and decide whether they are mistakes or real.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
import pandas as pd members = pd.DataFrame({ "name": ["Maya Reed", "Marco Hill", "Maya Reed", "Lena Park"], "email": ["maya.reed@example.com", "marco.hill@example.com", "mayareed@newmail.example.com", "lena.park@example.com"], "joined": ["2026-01-10", "2026-02-03", "2026-05-21", "2026-03-14"], }) latest = members.sort_values("joined").drop_duplicates(subset="name", keep="last") print(len(members), len(latest)) print(latest.loc[latest["name"] == "Maya Reed", "email"].tolist())
Output4 3
['mayareed@newmail.example.com']Four rows became three members, and Maya's new address stayed. Because sort_values("joined") puts the rows in date order, keep="last" means "the latest record". The dates are strings in the form "YYYY-MM-DD", so sorting them as strings also gives the right result; if they were in the form "DD.MM.YYYY", you would have to convert them to dates first.