TExcelTAD
Home › pandas › Cleaning Data

Cleaning Data

Real data is messy. Sensors drop readings, people type dates in five different formats, a form gets submitted twice, someone enters an age of 430. Data cleaning means finding and fixing these problems before you analyse anything, because every later result depends on it. Analysts often say that cleaning takes most of the time in a project, and it is time well spent.

The four classic problems

Problem Example Lesson
Empty cells a missing temperature reading Cleaning Empty Cells
Data in the wrong format "2024/03/05" and "5 March 2024" in one column, numbers stored as text Cleaning Wrong Format
Wrong data a delivery that took -3 days, a person 430 years old Cleaning Wrong Data
Duplicates the same order recorded twice Removing Duplicates

Our messy dataset

The next lessons all work on variations of this small log from a café's coffee machine. Each row is one day: the date, how many cups were brewed, the water temperature and how many kilowatt-hours of power the machine used. Look closely: every one of the four problems is hiding in it.

python · try it yourself
import io
import pandas as pd

csv_text = """day,date,cups,water_temp,kwh
1,2024-06-03,142,93.5,4.1
2,2024-06-04,155,94.0,4.4
3,2024-06-05,,93.8,4.2
4,2024-06-06,138,92.9,
5,20240607,149,93.1,4.3
6,2024-06-08,1610,93.6,4.6
7,2024-06-09,160,93.3,4.5
7,2024-06-09,160,93.3,4.5
9,,151,94.2,4.3
10,2024-06-12,147,9.4,4.2
"""
log = pd.read_csv(io.StringIO(csv_text))
print(log)
   day        date    cups  water_temp  kwh
0    1  2024-06-03   142.0        93.5  4.1
1    2  2024-06-04   155.0        94.0  4.4
2    3  2024-06-05     NaN        93.8  4.2
3    4  2024-06-06   138.0        92.9  NaN
4    5    20240607   149.0        93.1  4.3
5    6  2024-06-08  1610.0        93.6  4.6
6    7  2024-06-09   160.0        93.3  4.5
7    7  2024-06-09   160.0        93.3  4.5
8    9         NaN   151.0        94.2  4.3
9   10  2024-06-12   147.0         9.4  4.2

Spot the problems:

  • Empty cells: day 3 has no cups, day 4 has no kwh, day 9 has no date.
  • Wrong format: day 5's date is written 20240607 without dashes.
  • Wrong data: day 6 brewed 1610 cups (probably 161 with an extra zero), and day 10's water was 9.4 degrees (a misplaced decimal point: 94).
  • Duplicates: day 7 appears twice.

Detecting problems with code

Eyeballing works for ten rows, not for ten thousand. These one-liners find each kind of problem automatically:

python · try it yourself
import io
import pandas as pd

csv_text = """day,date,cups,water_temp,kwh
1,2024-06-03,142,93.5,4.1
2,2024-06-04,155,94.0,4.4
3,2024-06-05,,93.8,4.2
4,2024-06-06,138,92.9,
5,20240607,149,93.1,4.3
6,2024-06-08,1610,93.6,4.6
7,2024-06-09,160,93.3,4.5
7,2024-06-09,160,93.3,4.5
9,,151,94.2,4.3
10,2024-06-12,147,9.4,4.2
"""
log = pd.read_csv(io.StringIO(csv_text))

print("Missing values per column:")
print(log.isna().sum())

print("Duplicate rows:", log.duplicated().sum())

print("Dates not shaped like YYYY-MM-DD:")
print(log.loc[~log["date"].str.match(r"\d{4}-\d{2}-\d{2}", na=False), ["day", "date"]])

print("Suspicious values:")
print(log[(log["cups"] > 500) | (log["water_temp"] < 80)])
Missing values per column:
day           0
date          1
cups          1
water_temp    0
kwh           1
dtype: int64
Duplicate rows: 1
Dates not shaped like YYYY-MM-DD:
   day      date
4    5  20240607
8    9       NaN
Suspicious values:
   day        date    cups  water_temp  kwh
5    6  2024-06-08  1610.0        93.6  4.6
9   10  2024-06-12   147.0         9.4  4.2

You don't have to understand every expression yet; each is explained in the coming lessons. The point is that every check is a short, repeatable line of code.

Clean with code, not by hand

It's tempting to open the file in a spreadsheet and fix the cells manually. Resist that:

  • Repeatable: next month's file will have the same problems. A script fixes it again in a second.
  • Documented: the code is a record of exactly what you changed and why.
  • Safe: the original file stays untouched, so you can always start over.

Tip: Most pandas methods return a new object and leave the original alone. Assign the result (log = log.dropna()) when you want to keep the change. You will see inplace=True in older tutorials; the pandas developers now recommend plain assignment instead.

A cleaning checklist

  1. Look at the data: head(), info(), describe().
  2. Fix the types: dates to datetimes, numbers stored as text to numbers.
  3. Handle empty cells: drop the rows or fill them with a sensible value.
  4. Fix or remove wrong values.
  5. Remove duplicates.
  6. Check again: info() and describe() should now look sensible.

Test yourself

Which line counts the missing values in each column?

  1. df.count()
  2. df.isna().sum()
  3. df.missing()
  4. df.null_count

Why is cleaning data with a script better than fixing cells by hand?

  1. Scripts never make mistakes
  2. It is repeatable and documents every change
  3. Spreadsheets cannot open CSV files
  4. pandas refuses to read edited files