Artificial Intelligence Fundamentals / Prepare Data for Learning

Inspect a dataset

Lesson 6 of 26. Open to read. No account needed.

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:

A small table of orders. Each row is labelled as one sample, one order. The columns items, weight_kg and delivery are labelled as features; a note says that order_id only names the row and is not a feature. The last column, late, is labelled as the label, the answer a model would learn to predict. One empty weight_kg cell is marked as a missing value, and one delivery cell spelled Express with a capital E is marked as an inconsistent category.

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 NaN in the features: training stops with ValueError: Input X contains NaN. You must decide what to do about each gap, preferably by finding the real value.
  • Inconsistent categories. Express and express look 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.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/inspect-wine
    cd ~/ai-practice/inspect-wine
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\inspect-wine
    cd $HOME\ai-practice\inspect-wine
    

    The 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 empty weight_kg cell. Save this as orders.csv in 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,0
    

    Then save this as inspect_wine.py in 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())
    
  2. Run the script:

    python inspect_wine.py
    

    Output, 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 seeLikely causeNext 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 nameRun 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 spaceMake the first line of orders.csv match the listing exactly
weight_kg shows 0 missing valuesThe empty cells were filled in while saving, or the editor added spacesSave the CSV again exactly as shown, with ,, in two lines
Your editor saved the file as orders.csv.txtSome editors add an extensionSave as plain text named exactly orders.csv; ls shows the real name
ModuleNotFoundError: No module named 'pandas'The course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf inspect-wine
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse inspect-wine
    ls
    

    Check that the first ls shows inspect-wine before 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

  1. A colleague tries to train a model on the original orders.csv and gets ValueError: Input X contains NaN. What does the message mean, and what should they do before training?
  2. They then train a model to predict late and include late among the features. Test accuracy, the share of test samples labelled correctly, is 100%. What went wrong?
  3. In a describe() summary of a 500-row table, one column shows a count of 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

  1. 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.
  2. 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.
  3. Twenty values in that column are missing, because count includes only non-missing values.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy