Lesson 22 of 228 min
Cleaning a table
Before any model, look at the table: fix what is broken, keep what is rare but true, and check that the label means what you want to predict.
After this lesson you can look at a new table before you model it, mend what is broken in it, and check that its label is what you mean to predict.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
See where the gaps are
Put bank-additional-full.csv from UCI Bank Marketing next to your notebook. Use info() for the row count, types, and non-missing counts. The bank wrote some missing answers as "unknown", so pandas counts those as text. Count them separately.
import pandas as pd
calls = pd.read_csv("bank-additional-full.csv", sep=";")
calls.info()
print("Unknown education:", calls["education"].eq("unknown").sum())<class 'pandas.DataFrame'> RangeIndex: 41188 entries, 0 to 41187 … memory usage: 9.1 MB Unknown education: 1731
Make text consistent
Trim the spaces and standardize capitalization before you count names. This works when the case and spaces carry no meaning. Leave the original column in place so you can see what changed.
names = pd.Series([" Male", "Male", "New York", "new york"])
print(names.str.strip().str.lower().value_counts().to_dict()){'male': 2, 'new york': 2}Read dates as dates
Put hour.csv from UCI Bike Sharing next to the notebook. The date comes in as text. Give pandas the expected format, then count any conversions that left a gap.
bikes = pd.read_csv("hour.csv")
dates = pd.to_datetime(bikes["dteday"], format="%Y-%m-%d", errors="coerce")
print(dates.dtype, int(dates.isna().sum()))datetime64[us] 0
Make a feature from two columns
Put auto-mpg.data from UCI Auto MPG next to the notebook. Read ? as missing and divide weight by horsepower. This gives you pounds per horsepower. A missing horsepower stays missing in the new column.
columns = ["mpg", "cylinders", "displacement", "horsepower", "weight",
"acceleration", "year", "origin", "name"]
cars = pd.read_csv("auto-mpg.data", sep=r"\s+", names=columns, na_values="?")
cars["pounds_per_hp"] = cars["weight"].div(cars["horsepower"])
print(cars["pounds_per_hp"].head(3).round(1).tolist())
print("Missing:", cars["pounds_per_hp"].isna().sum())[27.0, 22.4, 22.9] Missing: 6
Scan a new table
A skrub TableReport gives you a quick view of a table’s columns and values. skrub deduplicate can suggest groups of similar spellings. Look at the rare values yourself before you merge any of them.
brands = cars["name"].str.split().str[0]
print(brands.value_counts().loc[["chevrolet", "chevy", "chevroelt"]])name chevrolet 43 chevy 3 chevroelt 1 Name: count, dtype: int64
Check the label with your own eyes
Obermeyer and colleagues found that healthcare spending stood in for health needs. At the same risk score, Black patients were sicker than White patients. Tools such as cleanlab can flag labels for a person to review. Start with a few bank rows and ask what each no measures.
short_calls = calls.loc[calls["duration"].lt(10), ["duration", "y"]]
print(short_calls["y"].value_counts().to_dict())
print(short_calls.sample(3, random_state=7).to_string(index=False)){'no': 290}
duration y
8 no
7 no
6 noRun on Python 3.13, pandas 3.1.1 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Tables with pandas
mass is the table's body_mass_g column, one mass for each penguin. What does mass > 4500 give?
2 of 3
A store wants to predict who will like a new product. Its label says if a customer bought it in the first week. What does a "no" in that label tell you?
3 of 3
Four cars, and one has a question mark for its horsepower, so the column came in as text. A mean in pandas skips gaps. What does this print?
import pandas as pd
cars = pd.DataFrame({"horsepower": ["130", "170", "?", "150"]})
hp = pd.to_numeric(cars["horsepower"], errors="coerce")
print(len(hp), hp.mean())The ideas in this lesson
- A first look
- Before any model, check a table's size, each column's type, its smallest and largest values, and how often each answer appears.
- Cleaning a table
- Drop the copies, turn text back into numbers, write one thing one way, and make what can't be true a gap.
- Checking the label
- A label is what someone wrote down: ask where it came from, what it stands for, and read some rows for mistakes.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Cleaning a table
Here's a bet. Every table in this course came ready to use. In the project, you'll bring a table of your own. It opens with no error at all. Is it ready for a model?
Keep your bet
Keep your bet in mind. A bank called its customers to offer a savings deposit, and it wrote down every call. Here's its table, as the file really comes. Before you cook, you look through the groceries. Before you train a model, you look through the table.
The size
A first look comes before any model.
pandas reads the bank's file into a table, with one line of code and no error. Forty-one thousand rows... and one column. Spot what's wrong.
All twenty-one column names are run together in one. The file puts a semicolon between its values, and pandas looked for commas. So you tell pandas the separator. Now it's forty-one thousand rows and twenty-one columns.
Opening with no error didn't mean it was ready.
Each column's type
Next, each column's type. A column holds numbers, or text. Ten of these hold numbers, like age. Eleven hold text, like job. Each one is the kind it should be. And if a column of numbers ever comes in as text? Then something in it isn't a number.
The smallest and the largest
Now the values. For each column of numbers, look at its smallest and largest value. Age runs from seventeen to ninety-eight. A customer of ninety-eight is rare, but real. It's rare, but it's true, so you keep it. Deleting the odd values throws away real customers.
A value that can't be true
The days since an earlier call are stranger. Most of them say nine hundred ninety-nine. Almost forty thousand calls, all exactly nine hundred ninety-nine days after an earlier call? While every other count stops at twenty-seven?
No. A value that can't be true is a code, or a mistake.
This one is a code. It means never called. So it's a gap: a missing answer, written as a number. Filling it and flagging it is part of preparing the features.
Count the words
For each column of text, count how often each answer appears.
"Unknown" turns up in six columns: the bank didn't know the answer. That's another gap, written as a word, and it gets a column of its own when you prepare the features. So a first look checks four things. The size, each column's type, the smallest and largest values, and how often each answer appears.
Rows that repeat
Cleaning a table means fixing what a first look finds.
Start with the rows. Ask pandas for rows that repeat a row above them, and it finds twelve. So twelve calls appear twice.
Each pair matches in all twenty-one columns. The customer, the month and the day match, and even the call's length in seconds. Could two different calls match that well? Not really. It's a copy, called a duplicate. A copy counts twice.
And its twin can land in the test rows: a leak, since the model is tested on a call it learned from. So drop the copies.
Twelve fewer rows, and every call is there once.
A number read as text
The bank's file has no column of numbers that came in as text. A lot of files do. Here's a real table of cars from the seventies and early eighties. Its horsepower comes in as text. Spot why.
Six cars have a question mark for their horsepower. One value that isn't a number makes the whole column text.
And a model stops: "could not convert string to float." It can't turn that text into a number.
One line turns the column into numbers. The six question marks become NaN: gaps.
One brand, three ways
Now take each car's brand, the first word of its name. Count how often each one appears, and read the bottom of the list.
Chevrolet, chevy, and chevroelt. How many brands is that?
To you, it's one brand.
One is a short name, and one is a spelling mistake. To the computer, they're three different words.
So a model learns three brands, and the small ones from just a few cars. So write each brand one way. Thirty-seven spellings become thirty brands.
A broken reading
One more fault. A table of bike rentals in Washington also keeps the weather. On one day in March, the humidity, how much water is in the air, reads zero, all day long.
And light rain fell nearly every hour.
Air can't be dry in the rain, and the data has no code for it. It's a broken reading. A broken egg goes in the trash. But a broken value just becomes a gap, and you keep its row.
Where the label comes from
A model learns to give the answer in one column: the label. The bank's label says if the customer opened a savings deposit. The bank wrote it down after its calls. About one in nine said yes. So for every label, ask who wrote it down, and when.
A label that stands in
The call's length is known only after the call, so it never goes into the model. But it can check the label. Take the shortest calls. Two hundred ninety lasted less than ten seconds. How many of them ended in a yes?
None. Every one is a no. Ten seconds is barely time to say hello, let alone hear an offer. So "no" doesn't always mean they didn't want one. It means they didn't open one. The bank wants to know who would want a deposit. The label says who opened one. Similar, but not the same thing.
Wrong labels
And labels can be plain wrong. People write them, and people make mistakes. A study checked the test sets of ten famous datasets. At least three labels in every hundred were wrong.
And in ImageNet's photos? At least six.
So before you trust a label, read some rows yourself. For each one, ask: would I write the same label?
In code
In real code, a first look is a few lines of pandas. Read the file with its separator. Then look at its shape, each column's type, and the smallest and largest values. Count the rows that repeat, drop them, and count the label.
Then write each check as an assert: a line that stops the code when its check fails.
Next month's file goes through the same checks, before the model sees it.
Now run the check for copies on the file as it came, before the copies were dropped. Will it pass?
It stops, and it tells you why. So the problem is found before a model learns from it.
In the project, run these lines first, on your own table.
Three looks
So, look first: the size, the types, the smallest and largest, and the words.
Fix what's broken. Keep what's rare but true.
Make what can't be true a gap.
And check what the label really means.
Look before you train
A model learns from the table you give it, mistakes and all. So look before you train. Now try it on this lesson's page, and take the quiz. Sort all ten findings, and try to get every one right.
Facts last checked on .
