Live build, 12–13 Dec: turn an app agentic, no fee. Register →

Courses / Data Science & ML with AI

Session 2 of 8

How to Clean Data with pandas: Missing Values, Duplicates

Notes

How to Clean Data with pandas: Missing Values, Duplicates and Data Types

Course: Data Science & ML with AI

Before you start

You need Python 3 with pandas, numpy and scikit-learn installed (pip install pandas numpy scikit-learn). The datasets bundled with scikit-learn arrive already clean, so the teaching examples build a small messy table in code, and the practice at the end damages a copy of scikit-learn’s bundled wine dataset for you to repair. There is nothing to download, no account and no API key. You should be able to read a few lines of Python and know that a table has rows and columns. If you have read the previous chapter, you know that the third stage of a project is to explore and clean the data; this chapter is that stage in detail.

Keep one question in mind while you read: how do I know a cleaned table is really clean, and not just a table in which the problems have been hidden? By the end you will have a short set of checks that answer it, including for cleaning code written by an AI assistant.

Summary

Real tables arrive with gaps, repeated rows, numbers stored as text and the same value spelled three ways, and a model or a report built on them quietly learns or repeats those errors. Cleaning with pandas has four jobs: inspect the table first, decide what to do with each missing value, remove repeated rows, and convert columns to the types and spellings the analysis needs. Each repair is a choice (drop, fill or keep), and each choice changes the numbers that come out later. The proof that cleaning worked is not that the code ran without an error but that row counts match what you predicted and a few assert statements about the result all pass. This chapter builds one small messy table and cleans it step by step, then trains you to check an AI assistant’s cleaning code with the same counts and asserts.

Key concepts

Term Definition
DataFrame pandas’ table type: rows and columns where every column has its own data type.
Missing value A cell with no usable value. pandas marks None, NaN and, for dates, NaT as missing. An empty string or the text n/a is ordinary text, not a missing value.
NaN / NaT The markers pandas uses for a missing number (NaN, “not a number”) and a missing date (NaT, “not a time”).
Dropping Removing rows (or columns) that contain missing values with dropna. Simple, but every dropped row is information lost.
Imputation (filling) Replacing a missing value with a stand-in, such as the column median, using fillna. Keeps the row, but the stand-in is a guess.
Duplicate row A row whose values repeat another row’s values across the columns considered. duplicated flags them and drop_duplicates removes them.
Data type (dtype) The kind of value a column holds, such as integer, decimal number, text or datetime. Arithmetic only works as intended on numeric dtypes.
Coercion Converting a column to a type and turning any value that cannot be converted into a missing value, as errors="coerce" does.
Inconsistent text The same real-world value written several ways, such as Pune, pune and PUNE, so a program counts them as different values.
Median The middle value when numbers are sorted. A common stand-in for missing numbers because a few extreme values do not move it.
Assertion A line of code (assert condition) that stops the program with an error if the condition is false. Used to state what a clean table must look like.
Row-count log The row count written down after each cleaning step, so every loss of rows is visible and can be explained.

Explanations

The failure, before the explanation

Meet a table of ten orders from a small online shop. Run this yourself; the figures are invented but every number below is computed from them.

import numpy as np
import pandas as pd

pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 20)

orders = pd.DataFrame({
    "order_id": [101, 102, 103, 104, 104, 105, 106, 107, 108, 109],
    "city": ["Pune", "pune ", "Delhi", "Delhi", "Delhi", "Mumbai", None, "Mumbai", "DELHI", "Pune"],
    "quantity": [2, 1, np.nan, 3, 3, 5, 2, np.nan, 4, 1],
    "price": ["$20.00", "$15.50", "$30.00", "$12.00", "$12.00", "$8.25", "$40.00", "n/a",
              "$18.00", "$22.50"],
    "order_date": ["2025-01-05", "2025-01-06", "2025-01-06", "2025-01-08", "2025-01-08",
                   "2025-01-09", "2025-01-10", "2025-01-11", "2025-01-12", "2025-13-01"],
})
print(orders)
   order_id    city  quantity   price  order_date
0       101    Pune       2.0  $20.00  2025-01-05
1       102   pune        1.0  $15.50  2025-01-06
2       103   Delhi       NaN  $30.00  2025-01-06
3       104   Delhi       3.0  $12.00  2025-01-08
4       104   Delhi       3.0  $12.00  2025-01-08
5       105  Mumbai       5.0   $8.25  2025-01-09
6       106     NaN       2.0  $40.00  2025-01-10
7       107  Mumbai       NaN     n/a  2025-01-11
8       108   DELHI       4.0  $18.00  2025-01-12
9       109    Pune       1.0  $22.50  2025-13-01

An analyst is asked three simple questions and answers them without looking at the table first. How many orders came from each city? What was the total price? How many items were ordered?

print(orders.groupby("city").size())
print(orders["price"].sum())
print(orders["quantity"].sum(), orders["quantity"].count())
city
DELHI     1
Delhi     3
Mumbai    2
Pune      2
pune      1
dtype: int64
$20.00$15.50$30.00$12.00$12.00$8.25$40.00n/a$18.00$22.50
21.0 8

No line raised an error, and all three answers are wrong. The city report has five groups for what are really three cities, and it silently leaves out order 106, whose city is missing. The “total price” is not a number at all: the prices are text, so sum glued the strings together. The item count of 21.0 ignores two orders whose quantity is missing, because sum skips missing values and count shows only 8 of the 10 rows contributed. Order 104 appears twice, so everything it touches is counted twice. The rest of this chapter takes these defects one at a time. A model trained on this table would learn from all of them without a word of complaint, which is why cleaning belongs before modelling.

Look first: shape, types and missing counts

Before you change anything, look. A doctor takes a history before prescribing. Three one-line checks give you the history of a table:

print(orders.shape)
print(orders.dtypes)
print(orders.isna().sum())
print(orders.duplicated().sum())
(10, 5)
order_id        int64
city              str
quantity      float64
price             str
order_date        str
dtype: object
order_id      0
city          1
quantity      2
price         0
order_date    0
dtype: int64
1

Read it line by line. The table has 10 rows and 5 columns. dtypes lists what pandas thinks each column holds: price and order_date are str (text), which already explains the broken total. (The pandas documentation notes that since version 3 text columns get the dtype str; older versions print object.) quantity is a decimal type, float64, even though quantities are whole numbers, because pandas’ default integer type cannot hold NaN, so a column of whole numbers with a gap is stored as decimals. isna().sum() counts missing values per column: one city and two quantities, three in all. duplicated().sum() counts rows that repeat an earlier row: one.

Notice what the count of three missing values does not show. Row 7 holds the text n/a as its price and row 9 holds the impossible date 2025-13-01 (there is no month 13). The pandas documentation says that empty strings are not counted as missing, and the same holds for any text such as n/a. isna marks None, NaN and NaT as missing, and its documentation lists no other value. So the first look must also include your own eyes on the values, and the type conversions later in this chapter turn these hidden problems into visible ones.

Missing values: drop, fill or keep

Imagine a paper form where some boxes were left empty. You can throw away every form with an empty box, you can fill each empty box with a sensible default, or you can keep the form and remember that the box is empty. The same three choices exist for a DataFrame.

Drop. dropna removes rows that contain missing values. By default it drops a row if any column is missing. Run it on the orders:

print(len(orders), len(orders.dropna()))
10 7

Three of the ten rows are gone because one cell in each was empty. When the table is large and only a few rows are affected, that can be fine. When many rows are affected, you lose most of your data to a handful of empty cells. The subset option narrows the damage: dropna(subset=["price"]) looks only at the price column.

Fill. fillna replaces missing values with a value you choose. The usual stand-in for a missing number is a typical value from the same column. The mean is the sum divided by the count; the median is the middle value. Compare them:

print(orders["quantity"].mean(), orders["quantity"].median())
filled = orders["quantity"].fillna(orders["quantity"].median())
print(filled.tolist())
2.625 2.5
[2.0, 1.0, 2.5, 3.0, 3.0, 5.0, 2.0, 2.5, 4.0, 1.0]

Both are computed over the eight known quantities (missing values are skipped). The fill worked, but look at what it produced: 2.5 items, a quantity that cannot exist. A filled value is a guess, and a guess has to make sense for the column. For a count of items you would round, or fill with the most common whole value. Also note that this median includes the duplicated row 104 twice; once the duplicate is removed the median becomes 2.0, which is the first sign that the order of cleaning steps matters.

Avoid filling with 0 just to make the gaps vanish. For a quantity, 0 means “ordered nothing”; for a price, it means “free”. Both are claims the data did not make, and they pull averages down.

Keep. Sometimes the honest answer is to leave the gap, or to fill it with a label. A missing city can become the text Unknown, which keeps the row and states plainly that the value was not known. Which of the three is right depends on the question: ask what the missing cell would have meant and what a wrong guess would cost.

Duplicate rows

Picture a customer who double-clicks the “place order” button, so the shop’s database records one purchase twice. In the table that is order 104. A duplicate row is a row whose values repeat another row’s values. duplicated returns a True/False value per row, and drop_duplicates removes the repeats:

print(orders.duplicated().sum())
deduped = orders.drop_duplicates()
print(len(orders), len(deduped))
print(deduped.index.tolist())
print(orders["order_id"].is_unique, deduped["order_id"].is_unique)
1
10 9
[0, 1, 2, 3, 5, 6, 7, 8, 9]
False True

Row 4 was the repeat, so it is gone; the index keeps its old labels, and the gap at 4 shows it. Two details matter. First, by default a row counts as a duplicate only when all columns match, and the keep option decides which copy survives: the first (the default), the last, or none. Second, duplicates are defined by the columns you consider. If only order_id should be unique, duplicated(subset="order_id") checks that column alone, which is stricter and sometimes finds repeats that differ in a minor column such as a timestamp. Decide what makes a row “the same thing” before you remove anything.

Removing duplicates is not always right. Two different customers can legitimately place an identical order on the same day. The check that guards you is a column that should be unique, such as an order id: is_unique returned False before and True after.

Wrong data types and messy text

A column of prices that looks like numbers but is stored as text is like a ruler printed in words: you can read it, but you cannot measure with it. The data type of a column decides what operations mean. Text added together is glued together, as the broken total showed.

Convert text to numbers in two steps: strip the characters that are not part of the number, then convert. pd.to_numeric does the conversion, and its errors option decides what happens to a value that will not convert:

price_num = pd.to_numeric(orders["price"].str.replace("$", "", regex=False), errors="coerce")
print(price_num.tolist())
print(price_num.dtype)
[20.0, 15.5, 30.0, 12.0, 12.0, 8.25, 40.0, nan, 18.0, 22.5]
float64

With the default errors="raise", the same call stops with ValueError: Unable to parse string 'n/a' at position 7. With errors="coerce", each bad value becomes NaN. This is the step that turns the hidden n/a into a counted missing value, which you can then drop, fill or keep. Coercion is a choice with a cost: it hides which values were bad unless you count them afterwards. Count the new missing values (price_num.isna().sum() is 1) and compare the count with what you expected.

Dates work the same way. pd.to_datetime with an explicit format parses text into real dates, and errors="coerce" turns anything that does not match, such as month 13, into NaT:

dates = pd.to_datetime(orders["order_date"], format="%Y-%m-%d", errors="coerce")
print(dates.dtype)
print(dates.isna().sum())
datetime64[us]
1

Once a column is a real datetime you can sort by it, subtract dates and group by month. Giving the format explicitly matters: it states what you expect, so a surprise becomes a visible NaT rather than a silent mis-reading.

Inconsistent text is a data-type problem of its own. Pune, pune (with a trailing space) and DELHI are the same cities to a person and different values to a program. Two string methods repair most of it: str.strip() removes leading and trailing whitespace and str.title() makes the capitalisation uniform.

city = orders["city"].str.strip().str.title()
print(orders["city"].tolist())
print(city.tolist())
print(city.nunique(), city.nunique(dropna=False))
['Pune', 'pune ', 'Delhi', 'Delhi', 'Delhi', 'Mumbai', nan, 'Mumbai', 'DELHI', 'Pune']
['Pune', 'Pune', 'Delhi', 'Delhi', 'Delhi', 'Mumbai', nan, 'Mumbai', 'Delhi', 'Pune']
3 4

Three real cities remain, and the missing city is still missing (nunique skips it by default; with dropna=False it counts as a fourth value). The trailing space in 'pune ' is invisible when the table is printed, but the tolist() output shows it between quotes; printing a list with its quotes is a cheap way to see stray whitespace.

Putting it together and proving it worked

Imagine handing the cleaned orders table to a colleague who asks, “How many rows did you drop, and why?” If your only answer is “it looked fine”, they have no reason to trust it. Two habits give you a real answer. First, write the cleaning as one function that works on a copy and keeps a row-count log, so every lost row has a reason. Second, finish with assert statements that describe what a clean table must look like. An assertion stops the program with an error if its condition is false, so a wrong table cannot slip through unnoticed.

def clean_orders(raw):
    df = raw.copy()
    log = [("start", len(df))]
    df = df.drop_duplicates()
    log.append(("after drop_duplicates", len(df)))
    df["city"] = df["city"].str.strip().str.title().fillna("Unknown")
    df["price"] = pd.to_numeric(df["price"].str.replace("$", "", regex=False), errors="coerce")
    df["order_date"] = pd.to_datetime(df["order_date"], format="%Y-%m-%d", errors="coerce")
    df["quantity"] = df["quantity"].fillna(df["quantity"].median()).astype(int)
    df = df.dropna(subset=["price"])
    log.append(("after dropping missing price", len(df)))
    df = df.dropna(subset=["order_date"])
    log.append(("after dropping bad date", len(df)))
    return df.reset_index(drop=True), log

clean, log = clean_orders(orders)
for step, n in log:
    print(f"{step}: {n}")
print(clean)
print(clean.dtypes)
start: 10
after drop_duplicates: 9
after dropping missing price: 8
after dropping bad date: 7
   order_id     city  quantity  price order_date
0       101     Pune         2  20.00 2025-01-05
1       102     Pune         1  15.50 2025-01-06
2       103    Delhi         2  30.00 2025-01-06
3       104    Delhi         3  12.00 2025-01-08
4       105   Mumbai         5   8.25 2025-01-09
5       106  Unknown         2  40.00 2025-01-10
6       108    Delhi         4  18.00 2025-01-12
order_id               int64
city                     str
quantity               int64
price                float64
order_date    datetime64[us]
dtype: object

These decisions are stated, not hidden. A repeated row is dropped. A missing city becomes Unknown. Missing quantities get the median of the de-duplicated column (2), converted back to whole numbers. A missing price or an impossible date is dropped, because inventing either would put a false number into the table. Three rows were lost out of ten, and the log says where. Now the assertions:

assert len(clean) == 7
assert clean["order_id"].is_unique
assert clean["price"].notna().all() and (clean["price"] > 0).all()
assert clean["order_date"].notna().all()
assert set(clean["city"]) == {"Pune", "Delhi", "Mumbai", "Unknown"}
assert clean["quantity"].dtype == "int64"
print("all checks passed")
print("raw rows still", len(orders))
all checks passed
raw rows still 10

Each assertion encodes something you predicted before running the code: seven rows (ten, minus one duplicate, one missing price and one bad date), unique ids, positive prices, real dates, four spellings of city and whole-number quantities. If cleaning code fails any of them, you know where to look. The raw table is untouched (10 rows), because the function worked on a copy; keep the raw data so you can always rerun a changed rule.

With AI: check an assistant’s cleaning code with counts and asserts

An assistant can write cleaning code quickly, and it will look professional. What it cannot do is know your table’s quirks or your tolerance for guessing. Here is code produced for the prompt “Clean the orders table: remove duplicates, fix the city names, make price numeric, make quantity whole numbers and parse the dates”:

def ai_clean(raw):
    df = raw.drop_duplicates().copy()
    df["city"] = df["city"].str.lower()
    df["quantity"] = df["quantity"].fillna(0).astype(int)
    df["price"] = df["price"].str.replace("$", "", regex=False).replace("n/a", "0").astype(float)
    df["order_date"] = pd.to_datetime(df["order_date"], format="%Y-%m-%d", errors="coerce")
    return df

ai = ai_clean(orders)
print(len(ai))
print(ai)
9
   order_id    city  quantity  price order_date
0       101    pune         2  20.00 2025-01-05
1       102   pune          1  15.50 2025-01-06
2       103   delhi         0  30.00 2025-01-06
3       104   delhi         3  12.00 2025-01-08
5       105  mumbai         5   8.25 2025-01-09
6       106     NaN         2  40.00 2025-01-10
7       107  mumbai         0   0.00 2025-01-11
8       108   delhi         4  18.00 2025-01-12
9       109    pune         1  22.50        NaT

It runs without an error and the table looks tidy. The check is the one this chapter taught: predict the result, then test it. You expected seven rows, positive prices, real dates and three city spellings. Run the same checks on the assistant’s table:

print(ai["city"].nunique(), sorted(ai["city"].dropna().unique()))
print(ai["price"].min())
print(ai["order_date"].isna().sum())
print(round(ai["price"].mean(), 2), round(clean["price"].mean(), 2))
print(ai["quantity"].mean().round(3), clean["quantity"].mean().round(3))
for name, check in [
    ("7 rows", len(ai) == 7),
    ("cities", set(ai["city"].dropna()) == {"pune", "delhi", "mumbai"}),
    ("price>0", (ai["price"] > 0).all()),
    ("dates", ai["order_date"].notna().all()),
]:
    print(name, check)
4 ['delhi', 'mumbai', 'pune', 'pune ']
0.0
1
18.47 20.54
2.0 2.714
7 rows False
cities False
price>0 False
dates False

All four checks print False, and the failures name five flaws:

  1. The city names are still split. lower() fixed the capitals but not the trailing space, so pune and pune remain two values (4 values, not 3). The fix is str.strip() first.
  2. Missing prices became 0. Order 107 now has a price of 0.0, which says it was free. The mean price drops to 18.47 against 20.54 for the cleaned table. A missing price should be dropped or flagged rather than invented.
  3. Missing quantities became 0. Two orders now say nothing was ordered, so the average quantity is 2.0 against 2.714 in the cleaned table. A zero is a claim the data never made; the median of the known quantities, or a dropped row, would have been honest.
  4. The impossible date was only converted, not handled. coerce made it NaT (1 missing date), and nothing then dealt with it, so a row with no date went on.
  5. The row count is 9, not 7. The code never dropped a row for a missing price or date, so the assertion len == 7 fails at once.

The skill is not rewriting the assistant’s code from memory. It is to write down what you expect the table to look like, run the counts and asserts, and let the failures point at the lines to change.

Three situations you will meet, and what they mean for your work

Before the table, three situations:

  1. A weekly sales report shows two Delhi rows, Delhi and DELHI, each with half the orders, and the regional manager asks why Delhi looks small.
  2. A colleague’s model is trained on a table where missing ages were filled with 0, and it predicts oddly for older customers.
  3. After a cleaning script runs, the table has 6,200 rows instead of the 9,800 you expected, and nobody can say where the rest went.
What you see Cleaning idea involved What to do
One real value in two spellings (situation 1) Inconsistent text Strip whitespace and standardise case, then count distinct values again and check the number matches the real list.
A stand-in that is not a plausible value (situation 2) Filling missing values Replace the 0 with a typical value such as the median, or drop the rows, and say which you chose.
Rows vanish with no explanation (situation 3) Row-count log Log the row count after every step and compare it with what you predicted; the step where it drops further than expected is the one to inspect.

Practice on your own: clean a messy copy of the wine dataset

Now clean a table nobody has cleaned for you. scikit-learn’s bundled wine dataset (178 wines, 13 measurements each) arrives tidy, so the code below damages a copy the way real exports get damaged: it blanks out 12 alcohol readings, repeats three rows and turns the magnesium column into text.

import numpy as np
import pandas as pd
from sklearn.datasets import load_wine

wine = load_wine(as_frame=True).frame
rng = np.random.default_rng(42)
messy = wine.copy()
gaps = rng.choice(len(messy), size=12, replace=False)
messy.loc[gaps, "alcohol"] = np.nan
messy = pd.concat([messy, messy.iloc[[3, 50, 120]]], ignore_index=True)
messy["magnesium"] = messy["magnesium"].astype(str)
print(messy.shape)
(181, 14)

Your task, without looking at the answer: (1) count the missing alcohol values, the duplicate rows and the type of the magnesium column; (2) remove the duplicates, make magnesium numeric and fill the missing alcohol values with the column’s median; (3) end with assert statements that prove the table has no duplicates and no missing alcohol values. Before you run step 2, write down how many rows you expect to have left.

Check your answer
print(messy["alcohol"].isna().sum(), messy.duplicated().sum(), messy["magnesium"].dtype)

clean = messy.drop_duplicates()
clean["magnesium"] = pd.to_numeric(clean["magnesium"])
clean["alcohol"] = clean["alcohol"].fillna(clean["alcohol"].median())
print(clean.shape, clean["alcohol"].isna().sum(), clean["magnesium"].dtype)

assert clean.duplicated().sum() == 0
assert clean["alcohol"].notna().all()
print("all checks passed")
12 3 str
(178, 14) 0 float64
all checks passed

You should find 12 missing values, 3 duplicate rows and a text column, and you should have predicted 178 rows: 181 minus the 3 repeats, which brings the table back to the dataset’s original size. If your count is lower than 178, a step dropped real rows; read your row-count log to find which one.

Flashcards

Say the answer aloud before revealing it. Speaking it is what exposes the gaps that reading past a written answer hides.

Which values does isna count as missing, and which does it miss?

It counts None, NaN and NaT as missing. Text such as an empty string or n/a is ordinary text, so isna does not count it, and it stays hidden until you convert the column.

What does dropna do by default, and how do you limit it to one column?

By default it removes every row that has a missing value in any column. Passing subset=["price"] makes it look only at the price column.

Why is filling a missing quantity with 0 usually a bad idea?

Zero is a real value that says “nothing was ordered”, a claim the data never made, and it pulls averages down. A typical value such as the median, a label or a dropped row is more honest.

Why can the median be a better stand-in than the mean?

The median is the middle value, so a few extreme values do not move it, while the mean is dragged toward them. It is still a guess, so check that the filled value makes sense for the column.

How do duplicated and drop_duplicates decide that a row repeats?

By default a row repeats when all of its columns match an earlier row. The subset option limits the comparison to chosen columns, and keep chooses which copy survives.

What does errors="coerce" do in to_numeric?

It turns any value that cannot be converted into NaN instead of raising an error. That hides which values were bad, so count the new missing values afterwards and compare with what you expected.

Why give to_datetime an explicit format?

The format states what you expect, so a value that does not match, such as month 13, becomes a visible NaT instead of being silently read some other way.

Why do Pune, pune and PUNE need cleaning?

A program compares text exactly, so each spelling is a separate value and counts or groups split. str.strip() and str.title() make them identical.

Why does the order of cleaning steps matter? Give the example from this chapter.

The median quantity was 2.5 with the duplicate order still present and 2.0 after drop_duplicates. A step that changes the rows changes any statistic computed afterwards.

What two habits prove that cleaning worked?

Keep a row-count log so every lost row has a stated reason, and finish with assert statements about the result, such as unique ids, positive prices and the expected number of rows.

Model answer

The question: “A new dataset lands on your desk. How do you clean it before analysis or modelling?” A strong answer hits five beats, in this order:

  1. Inspect — look at shape, data types, missing counts and duplicate counts before changing anything.
  2. Missing values — decide per column whether to drop, fill or keep, and say what each costs.
  3. Duplicates — decide what makes a row “the same”, then remove repeats.
  4. Types and text — convert numbers and dates to real types and make spellings consistent.
  5. Verify — log row counts and assert what a clean table must look like.

“I would start by looking at the table: its shape, the type of each column, and how many values are missing or repeated, and I would check the values by eye because text like n/a is not counted as missing. For missing values I decide column by column whether to drop the rows, fill with a plausible value such as the median, or keep a label like Unknown, because each choice changes later numbers. I remove duplicate rows after deciding which columns define a repeat. Then I convert prices and dates to proper types, coercing what will not parse and counting it, and standardise text with strip and case rules. Finally I prove the result: I write the row count after each step and add assertions, such as unique ids, no missing prices and the row count I predicted, and I keep the raw table so I can rerun the rules.”

Missing a beat is a failure state. Without inspect you do not know what is broken. Without a decision on missing values a stand-in such as 0 slips in unannounced. Without duplicates repeated orders are counted twice. Without types and text totals glue strings together and cities split into groups. Without verify nobody can tell a cleaned table from one where the problems were hidden, and that is the beat an examiner most often finds missing.

Why this matters

  • Trusting a report. A total or a count is only as good as the cleaning behind it; asking “how many rows were dropped, and why?” is the quickest check on any figure.
  • Protecting a model. A model learns whatever the table holds, including repeated rows and invented zeros, and it will not warn you. Cleaning is the cheapest place to prevent a bad model.
  • Reviewing AI-written code. An assistant writes tidy cleaning code that runs without error. Counts and asserts are how you tell code that is tidy from code that is correct.
  • Making work repeatable. Cleaning written as one function over a copy of the raw table can be rerun on next month’s data, and it shows a reviewer every decision you made.

After this unit

You can now inspect a messy table and clean it, and you can prove the result with row counts and assertions. The next chapter turns to the cleaned table itself: exploratory data analysis, reading summary statistics and drawing the charts that show the shape of the data, with a real dataset from scikit-learn.

Quiz

Answers are not marked on this page yet. Work through the questions and check the written ones against the criteria printed with each question. The answer key is kept back for now.

Quiz — How to Clean Data with pandas: Missing Values, Duplicates and Data Types

Instructions: Eight multiple-choice questions. Pick one option per question. Work closed-book, then compare your letters with the answer key, which is held separately and holds the reasons.


1. [recall] A pandas column holds None, NaN, NaT, an empty string and the text n/a. Which of these does isna() treat as missing?

a) All five, because each of them stands for a cell that has no usable value b) Only NaN, because None and NaT are converted to text when a column is loaded c) None, NaN, NaT and the empty string, but not the text n/a that was typed in d) None, NaN and NaT, while the empty string and the text n/a are ordinary text


2. [application] A column named price holds text such as "$20.00" and "n/a". The analyst wants a numeric column in which anything that cannot be read as a number becomes missing. Which line does that?

a) df["price"].astype(float) after the column has been sorted from smallest to largest b) pd.to_numeric(df["price"].str.replace("$", "", regex=False), errors="coerce") c) df["price"].fillna(0) so that every cell holds a number before any conversion d) pd.to_numeric(df["price"], errors="raise") so that any bad value is reported at once


3. [scenario] After cleaning, an analyst counts the distinct values of a city column and gets 4, but the shop only sells in 3 cities. Printing the values with quotes shows 'Pune', 'pune ', 'Delhi' and 'Mumbai'. What should the analyst do?

a) Strip the whitespace and standardise the capitalisation, then count the distinct values again b) Drop every row whose city appears fewer times than the other cities in the table c) Convert the column to a numeric type so that each spelling is replaced by a number d) Fill the column’s missing values with its most common city and count the values again


4. [application] A table has 10 rows. Three different rows each have exactly one missing cell, in different columns, and no other row has a gap. How many rows remain after df.dropna() with its default settings?

a) 3, because only the rows that contain a missing cell are kept b) 9, because dropping removes one row for each column that has a gap c) 7, because each of the three rows with a gap is removed d) 10, because dropping happens only when a whole row is empty


5. [recall] By default, when does drop_duplicates() treat a row as a repeat of an earlier row?

a) When the values in every column match the earlier row b) When the first column of the row matches the earlier row c) When the row has the same index label as an earlier row d) When at least one value in the row matches the earlier row


6. [scenario] A cleaning script is meant to turn 9,800 raw rows into a table of about 9,600. It runs without an error and returns 6,200 rows. What is the most useful next step?

a) Add rows from a backup file until the table has 9,800 rows again b) Train a model on the 6,200 rows and see whether its score is acceptable c) Fill every missing value with 0 so that no row is dropped any more d) Log the row count after each step and find the step where it fell too far


7. [application] A quantity column has the known values 2, 1, 3, 5, 2, 4 and 1, plus one missing value. The analyst fills the gap with the median of the known values. What value is used?

a) 5, the value that sits in the middle position of the original row order b) 2, the middle value once the seven known values are sorted c) 2.6, the sum of the seven known values divided by seven d) 1, the smallest value that is repeated in the column


8. [scenario] An assistant’s cleaning code replaces every missing price with 0. The analyst expects every cleaned price to be a sensible one. Which check shows the problem at once?

a) assert clean["price"].notna().all(), which confirms no price is missing b) assert clean["price"].dtype == "float64", which confirms the type is numeric c) assert (clean["price"] > 0).all(), which fails if any price is zero or negative d) assert clean["order_id"].is_unique, which confirms that no order appears twice

Want help building this with someone?

Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.

Ask about mentor-led training

TechEazy Consulting training material — not affiliated with or endorsed by pandas, scikit-learn or any other project or company named in this course.