Back to Tutorials
Python for AI
Beginner

Cleaning Data with pandas

Run a messy table through a cleaning script one line at a time, catch a filter quietly dropping a customer, and see what filling in blanks does to a survey’s answers.

10 minInteractive: drag, click and try things as you read


Real data arrives messy: the same city spelled five ways, numbers stored as text, duplicates, ages no one can be, and blanks. pandas, Python’s table library, fixes each of these in a line or two, which is why cleaning code tends to look the same in every project. But every one of those lines is a decision. Cleaning changes your data, so it changes your answers: know what each line keeps, drops and invents. Here you’ll run a cleaning script one line at a time, catch it quietly throwing away a customer, and see what filling in blanks does to a survey.

A cleaning script, one line at a time#

A pandas DataFrame is a table: named columns, one row per record, like a spreadsheet you can program. Here are twelve café loyalty sign-ups, typed in by hand. Most cleaning scripts follow the same order: remove duplicates, tidy the text, turn text into numbers, deal with impossible values, then deal with what’s missing.

Predict first

One line in the script removes impossible ages: df = df[df["age"].between(0, 120)]. Two customers have impossible ages (230 and −1). How many rows does that line remove?

Try it
Twelve made-up sign-ups with the mistakes hand-typed data usually has. Each step is what the pandas line beside it does, checked against pandas itself. Yellow cells just changed; struck-through rows were just removed. Stray spaces show as red dots.

Each line earns its place. drop_duplicates() removes rows that match exactly, so the two Bens go only because both copies have the same stray space. Stripping spaces and fixing capitals turns seven spellings into three cities. pd.to_numeric(..., errors="coerce") turns text into numbers and anything unreadable, like “N/A”, into a proper missing value (NaN), and only then can you take an average: 51.7, pulled up by someone aged 230.

Then the filter. Dropping impossible ages removes three customers, not two, and Leeds shrinks from three customers to one: anyone counting customers per city now gets the wrong answer. Blanking the impossible ages instead keeps all ten customers, and filling the three gaps with the median age (34) gives an average of 33.8. A filter drops whole rows, including the good information in them. Mark bad values as missing, and decide what to do with missing values in one place.

What to do about blanks#

Missing values are the hardest part, because the right fix depends on why they’re missing. Statisticians, following Donald Rubin in 1976, separate three cases: values missing completely at random (a coin flip, a glitch), missing at random given other columns you have (younger people skip a question more often), and missing because of the very value that’s missing (high earners skip the income question). The common pandas fixes are to drop the rows with dropna, or to fill the gaps with fillna: one typical value for everyone, or a typical value for each group.

Predict first

A survey asks 600 people their income, and 30% leave it blank at random. You fill every blank with the average of the answers you have. What happens to the average income?

Try it
600 made-up survey answers from three kinds of job, with every true income known, so you can compare each fix with the truth. “Run the survey again” redraws who leaves the question blank.

When the blanks are random, dropping them works: the answers that remain are a fair sample, and the average lands within about £1.5k of the true £39.4k. Filling with the mean keeps the average but invents about 180 identical incomes: the spread falls from 17.0 to about 14, and the share earning over £60k falls from 14.5% to around 10%. Filling with each job’s average is closer on the spread, though still a little narrow.

When high earners skip the question, every simple fix fails. Dropping the blanks or filling with the mean gives an average of £32k to £34k against a true £39.4k, and the share over £60k falls to a few percent. Filling by job helps (£36k to £37k), because more of the blanks come from tech jobs, but it fills each one with an average worked out from the people who did answer, who earn less. No line of code can recover information the blanks are hiding; you have to know why they’re there.

Habits that save you#

  • Look before you clean. df.info() shows each column’s type and how many values are missing; df.describe() shows ranges, where an age of 230 jumps out; df["city"].value_counts() shows every spelling.
  • Count rows after every step. A filter or a merge that loses rows you didn’t expect is the most common silent bug in data work.
  • Write the cleaning as a script, not by hand. When new data arrives, or someone asks why a number changed, you can rerun it and point to the line.
  • Keep the raw data. Clean into a new table, so you can always check what you changed.

In code#

The figure’s script, with the gentler choice for impossible ages (pip install pandas):

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "name":  ["Amira", "Ben", "Chloe", "Amira", "Dev", "Ella", "Femi", "Gus", "Ben", "Hana", "Ivan", "Jo"],
    "city":  ["London", "london ", "Leeds", "London", "LEEDS", "Manchester", "manchester", "London", "london ", " Leeds", "Manchester", "London"],
    "age":   ["34", "28", "N/A", "34", "230", "41", "19", "52", "28", "25", "-1", "37"],
    "spend": ["£4.50", "3.20", "£5.10", "£4.50", "£2.80", None, "£6.00", "£3.90", "3.20", "£4.20", "£5.50", "n/a"],
})

df = df.drop_duplicates()                                          # 12 rows -> 10
df["city"] = df["city"].str.strip().str.title()                    # 7 spellings -> 3 cities
df["age"] = pd.to_numeric(df["age"], errors="coerce")              # "N/A" becomes NaN
df["spend"] = pd.to_numeric(df["spend"].str.replace("£", ""), errors="coerce")
df.loc[~df["age"].between(0, 120), "age"] = np.nan                 # 230 and -1 become NaN, the rows stay
df["age"] = df["age"].fillna(df["age"].median())

print(df.to_string(index=False))
print(df["city"].value_counts().to_dict(), round(df["age"].mean(), 1), round(df["spend"].mean(), 2))
#  name       city  age  spend
# Amira     London 34.0    4.5
#   Ben     London 28.0    3.2
# Chloe      Leeds 34.0    5.1
#   Dev      Leeds 34.0    2.8
#  Ella Manchester 41.0    NaN
#  Femi Manchester 19.0    6.0
#   Gus     London 52.0    3.9
#  Hana      Leeds 25.0    4.2
#  Ivan Manchester 34.0    5.5
#    Jo     London 37.0    NaN
# {'London': 4, 'Leeds': 3, 'Manchester': 3} 33.8 4.4

Two spends are still missing. Whether to fill them, and how, is the same decision again: it depends on why they’re blank and what you’ll use the column for.

What to remember

  • A cleaning script is a series of decisions: drop duplicates, tidy text, convert types, handle impossible values, then handle missing ones.
  • Filters drop whole rows, including missing values you didn’t mean to drop; blank bad values instead, and count rows after every step.
  • Dropping or filling blanks works when they’re random; when the blank depends on the missing value itself, every simple fix is biased.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.