Look Before You Learn
A model learns whatever is in its data, including the mistakes. A missing value, a category spelled two ways or a column that should not be there will not stop you from writing training code, but it will change what the model learns, or make training fail with an error you then have to trace back. Five minutes of looking at the data first saves hours later.
This lesson shows what to look for and how to look, using pandas, the library for working with tables of data.
Samples, Features and Labels in a Table
pandas holds a table in a DataFrame: rows and named columns, like a spreadsheet. For machine learning, the table has a standard layout:

Read the diagram row by row, then column by column. Each row is one
sample. Most columns are features. One column is the label: the known
answer a model would learn to predict, here whether the order was late. An
identifier such as order_id is neither: it names the row but says nothing
about it, so it should not be used as a feature. The two marked cells are the
kinds of problem this lesson teaches you to find.
The Wine Data
scikit-learn includes a small wine dataset: the results of a chemical analysis of 178 wines grown in the same region of Italy by three different growers. Each wine has 13 measurements, such as alcohol content and colour intensity, and a label from 0 to 2 for the grower. It is a copy of a dataset first published by Forina and colleagues, and it ships inside scikit-learn, so loading it needs no download. Like all the bundled datasets, it is far smaller than real-world data.
Inspecting a DataFrame
These are the inspections you will use most:
df.shape # (number of rows, number of columns)
df.dtypes # the type of each column: numbers, text and so on
df.describe() # count, mean, spread, minimum and maximum of numeric columns
df["<column>"].value_counts() # how often each value appears in one column
df.isna().sum() # how many values are missing in each column
df stands for any DataFrame, and <column> for a column name. In a
DataFrame, a missing value appears as NaN, short for "not a number". When
pandas reads a file, an empty cell becomes NaN.
This course uses pandas 3.0. If you look up pandas examples elsewhere, check their version: pandas 3.0 changed some behaviour of earlier releases.
Problems to Look For
- Missing values. Most scikit-learn models refuse to train on data with
NaNin the features: training stops withValueError: Input X contains NaN.You must decide what to do about each gap, preferably by finding the real value. - Inconsistent categories.
Expressandexpresslook the same to a person, but to the computer they are two different categories. A model would learn them separately, and each would have fewer examples. - Columns that do not belong. Identifiers, and anything that gives the answer away, must not be used as features. The lesson on data leakage looks at the second case closely.
- Unbalanced classes. If one label is much rarer than the others, some ways of scoring a model become misleading, as the baseline lesson shows.
Exercise: Inspect the Wine Data
You will describe the wine dataset and then find the problems in a small table of orders.
Starting state: the course environment from the setup lesson, active in your terminal. The wine data ships with scikit-learn; you will save the orders table yourself.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/inspect-wine cd ~/ai-practice/inspect-wineWindows PowerShell:
mkdir $HOME\ai-practice\inspect-wine cd $HOME\ai-practice\inspect-wineThe orders table is a comma-separated values file: the first line names the columns, and each later line is one order. The two lines with
,,have an emptyweight_kgcell. Save this asorders.csvin that folder:order_id,items,weight_kg,delivery,late 1,3,2.5,standard,0 2,1,,express,0 3,5,7.0,Express,1 4,2,1.2,standard,0 5,4,,standard,1 6,1,0.4,express,0Then save this as
inspect_wine.pyin the same folder:"""Inspect the wine data, then a small table that has problems.""" import pandas as pd from sklearn.datasets import load_wine wine = load_wine(as_frame=True).frame # 13 measurements plus a "target" column print("Rows and columns:", wine.shape) print(wine.dtypes.value_counts()) print(wine[["alcohol", "color_intensity", "target"]].describe().round(2)) print("Samples per class:") print(wine["target"].value_counts().sort_index()) orders = pd.read_csv("orders.csv") print("Missing values per column:") print(orders.isna().sum()) print("Delivery options:") print(orders["delivery"].value_counts()) -
Run the script:
python inspect_wine.pyOutput, which should match exactly:
Rows and columns: (178, 14) float64 13 int64 1 Name: count, dtype: int64 alcohol color_intensity target count 178.00 178.00 178.00 mean 13.00 5.06 0.94 std 0.81 2.32 0.78 min 11.03 1.28 0.00 25% 12.36 3.22 0.00 50% 13.05 4.69 1.00 75% 13.68 6.20 2.00 max 14.83 13.00 2.00 Samples per class: target 0 59 1 71 2 48 Name: count, dtype: int64 Missing values per column: order_id 0 items 0 weight_kg 2 delivery 0 late 0 dtype: int64 Delivery options: delivery standard 3 express 2 Express 1 Name: count, dtype: int64
How the Script Works and What It Shows
Loading the wine data. load_wine(as_frame=True) returns the dataset with
pandas tables inside it, and .frame is a single DataFrame with the 13
measurement columns plus a target column holding the grower label. Hence
(178, 14): 178 samples and 14 columns, of which 13 are features and one is
the label.
Column types. wine.dtypes.value_counts() counts the column types: 13
columns of float64, numbers with decimals, and one of int64, whole
numbers. The whole-number column is target. All features are numeric, which
is what scikit-learn models need. The Name: count lines are pandas
describing the result itself; you can ignore them.
Summary statistics. describe() on three chosen columns gives, for each,
the number of non-missing values (count), the average (mean), how spread
out the values are (std, the standard deviation), and the minimum, quartiles
and maximum. .round(2) keeps two decimals. A count of 178 in every column
means no wine has a missing value here. The mean of target, 0.94, is
meaningless: the labels are names for growers stored as numbers, not
quantities. Always ask whether a statistic makes sense for the column.
Class balance. value_counts().sort_index() counts each label, sorted by
label: 59, 71 and 48 wines. No class is rare, so the three groups are
reasonably balanced.
The orders table. pd.read_csv("orders.csv") reads the file you saved
into a DataFrame. orders.isna().sum() counts missing values per column: two
in weight_kg, the two empty cells. value_counts() on delivery lists
three different values, standard, express and Express, although there
are really only two delivery options. If you deleted the .sum() from
orders.isna().sum(), you would see a whole table of True and False
values, one per cell, instead of one count per column.
Success: the output matches the listing above, and you can name the two
problems in orders.csv and the columns they affect.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
FileNotFoundError: [Errno 2] No such file or directory: 'orders.csv' | The script ran from another folder, or the CSV was saved elsewhere or under another name | Run pwd and ls; run the script from the folder that holds both files |
KeyError: 'delivery' | The column name in the CSV's first line differs from the script, for example a capital letter or a space | Make the first line of orders.csv match the listing exactly |
weight_kg shows 0 missing values | The empty cells were filled in while saving, or the editor added spaces | Save the CSV again exactly as shown, with ,, in two lines |
Your editor saved the file as orders.csv.txt | Some editors add an extension | Save as plain text named exactly orders.csv; ls shows the real name |
ModuleNotFoundError: No module named 'pandas' | The course environment is not active | Activate it and rerun |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf inspect-wine lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse inspect-wine lsCheck that the first
lsshowsinspect-winebefore removing it. Do the independent task first.
Independent task: extend inspect_wine.py so that it also prints the rows
of orders.csv that need fixing: those with a missing weight or a delivery
value that is not all lowercase. Then fix the file. The warehouse confirms
that order 2 weighed 0.8 kg and order 5 weighed 3.1 kg, and that there are
only two delivery options, standard and express. Run the script again and
check that no problems remain.
Check Your Understanding
- A colleague tries to train a model on the original
orders.csvand getsValueError: Input X contains NaN.What does the message mean, and what should they do before training? - They then train a model to predict
lateand includelateamong the features. Test accuracy, the share of test samples labelled correctly, is 100%. What went wrong? - In a
describe()summary of a 500-row table, one column shows acountof 480. What does that tell you?
Answer and Reasoning
Independent task
Add these lines at the end of the script:
print("Rows that need fixing:")
needs_fixing = orders["weight_kg"].isna() | (orders["delivery"] != orders["delivery"].str.lower())
print(orders[needs_fixing])
orders["weight_kg"].isna() is True for each row with a missing weight.
orders["delivery"].str.lower() converts every delivery value to lowercase,
so comparing it with the original with != is True wherever a value had
capital letters. The | symbol means "or". Using the combined True and
False values inside orders[...] keeps only the matching rows: orders 2, 3
and 5.
Then edit orders.csv: write 0.8 in order 2's empty weight, 3.1 in
order 5's, and change Express to express in order 3. After rerunning,
weight_kg shows 0 missing values, delivery lists only standard (3) and
express (3), and no rows need fixing.
Using the real values from the warehouse is the best fix. Without them, you would have to choose between removing the rows and filling the gaps with an estimate, and either choice changes what a model learns; record whichever you choose.
Understanding check
- Some feature values are missing, and the model cannot train on them. They
should find the missing values with
isna().sum()and fix them: ideally with the real values, otherwise by a recorded decision to remove or estimate them. - The label was used as a feature, so the model was given the answer. A perfect score here means nothing; a feature that contains the answer must be removed. The data leakage lesson returns to this.
- Twenty values in that column are missing, because
countincludes only non-missing values.