Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Clean real-world data

By the end of this chapter, you'll be able to

  • Standardise text with the str methods
  • Convert a column to numbers while isolating invalid values
  • Find and remove duplicates
  • Read dates without ambiguity and group by month

Standardise text

Python's string methods apply to a whole column through the .str accessor:

import pandas as pd

products = pd.Series(["Millet", " millet", "GROUNDNUT ", "cowpea", "Groundnut"])
print(products.value_counts())
clean = products.str.strip().str.lower()
print(clean.value_counts())
Millet        1
 millet       1
GROUNDNUT     1
cowpea        1
Groundnut     1
Name: count, dtype: int64
millet       2
groundnut    2
cowpea       1
Name: count, dtype: int64

Before cleaning, pandas sees five different products; after, three. strip() removes spaces at the start and the end, lower() puts everything in lower case. We chain them: each method returns a new Series.

Convert to numbers

pd.to_numeric converts a column to numbers. With errors="coerce", anything that cannot be converted becomes NaN instead of raising an error: you can then count and examine the rejected values.

import pandas as pd

prices = pd.Series(["1 500 F", "2000", "n/a", "1 250 F", "800"])
cleaned = prices.str.replace("F", "").str.replace(" ", "")
numbers = pd.to_numeric(cleaned, errors="coerce")
print(numbers.tolist())
print("Rejected values:", prices[numbers.isna()].tolist())
[1500.0, 2000.0, nan, 1250.0, 800.0]
Rejected values: ['n/a']

We first remove the unit and the spaces, then convert. Only “n/a” remains unconvertible: it becomes NaN, and you can find it in the original column to decide what to do with it.

Duplicates

A sale entered twice inflates every total. duplicated() marks the rows identical to an earlier row, drop_duplicates() removes them:

import io
import pandas as pd

csv = "date,product,customer,kg\n2026-03-02,millet,Coop A,120\n2026-03-02,millet,Coop A,120\n2026-03-03,cowpea,Coop B,45\n2026-03-03,cowpea,Coop C,45\n"
sales = pd.read_csv(io.StringIO(csv))
print(sales.duplicated().tolist())
print(len(sales.drop_duplicates()))
[False, True, False, False]
3

The two cowpea sales of 3 March are not duplicates: the customers differ. By default, every column must be identical. subset=["date", "customer"] would limit the comparison to some columns. Be careful: two identical sales can also be two real sales. A unique identifier per sale, in the source system, removes the doubt.

We convert the dates with an explicit format.

Step 5 of 5
Text description of the animation
  1. The raw values mix formats.
  2. We standardise the text so that the same products are recognised.
  3. We convert the numbers. Impossible values become NaN and are examined separately.
  4. We remove the duplicate entries.
  5. We convert the dates with an explicit format.

Dates

A date read from a CSV is text. pd.to_datetime turns it into a real date, which you can compute with, extract the month from or group by period. Always give the format when you know it:

import io
import pandas as pd

csv = "date,kg\n05/03/2026,120\n18/03/2026,80\n02/04/2026,200\n27/04/2026,60\n"
sales = pd.read_csv(io.StringIO(csv))
sales["date"] = pd.to_datetime(sales["date"], format="%d/%m/%Y")
print(sales["date"].dt.month.tolist())
print(sales.groupby(sales["date"].dt.to_period("M"))["kg"].sum())
[3, 3, 4, 4]
date
2026-03    200
2026-04    260
Freq: M, Name: kg, dtype: int64

%d/%m/%Y means day/month/4-digit year. The .dt accessor gives access to the parts of the date (year, month, day…), and to_period("M") maps each date to its month, which makes grouping possible.

Mini-lab: a list of products to cleanPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: hand-typed weights

The weight column was typed by hand: "120 kg", "85kg", " 200 KG", "?", "1,5 t". Convert it to kilograms (numbers), knowing that a tonne is 1,000 kg and that the comma is the decimal separator. Display the converted weights and the rejected values.

Hint 1
Start with str.strip().str.lower(), then spot the tonnes with str.endswith("t").
Hint 2
Remove the units with str.replace, replace the comma with a dot, then pd.to_numeric(…, errors="coerce"). Multiply the rows in tonnes by 1000 with loc.
Show the solution and common mistakes
import pandas as pd

weight = pd.Series(["120 kg", "85kg", " 200 KG", "?", "1,5 t"])
text = weight.str.strip().str.lower()
in_tonnes = text.str.endswith("t")
values = text.str.replace("kg", "").str.replace("t", "").str.replace(",", ".").str.strip()
kg = pd.to_numeric(values, errors="coerce")
kg.loc[in_tonnes] = kg.loc[in_tonnes] * 1000
print(kg.tolist())
print("Rejected:", weight[kg.isna()].tolist())
[120.0, 85.0, 200.0, nan, 1500.0]
Rejected: ['?']

Common mistakes:

  • Converting before replacing the comma: “1,5” is not a number for Python, and the row would be wrongly rejected.
  • Removing “t” before spotting the tonnes: the information is lost, and 1.5 t would become 1.5 kg. Keep it in a mask first, like in_tonnes.

Summary

  1. 1The .str accessor applies string methods to a whole column: strip, lower, replace…
  2. 2pd.to_numeric(…, errors="coerce") converts to numbers and turns invalid values into NaN, to be examined.
  3. 3duplicated and drop_duplicates find and remove duplicate rows.
  4. 4pd.to_datetime with an explicit format reads dates without ambiguity; .dt and to_period allow grouping by month.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.