Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Data Wrangling: Clean Data Before You Decide

Open In Colab

Data Wrangling: Clean Data Before You Decide

Real business data arrives messy: names spelled several ways, numbers stored as text, dates in three formats, rows entered twice, values missing, and the occasional typo that is ten times too large. This reading shows how to find and fix each problem with pandas, how to join two tables, and how to ask the same questions in SQL with DuckDB.

The running example is a real decision. Qahwa House buys milk from two suppliers and wants to keep only one. On the raw file one supplier looks better; on the cleaned file, the other one does. Wrangling is not housekeeping: it decides the decision.

After this reading you can:

  • check the type of every column and convert text to numbers and dates;

  • standardise labels, remove duplicates, and choose how to treat missing values;

  • flag outliers with the IQR rule and tell an error from a real extreme;

  • join two tables on a key and check the result;

  • write the same summary in pandas and in SQL.

Textbook: Albright & Winston, Chapter 2 (data types, missing values) and Chapter 18 (importing data).

1. The data: two tables

Qahwa House records every delivery of milk and coffee beans in a purchases table, typed in by staff at four branches. A second, small table describes each product the suppliers sell. Both are loaded below.

(644, 9) (4, 6)
Loading...
Loading...

The purchases table has one row per delivery: when, where, from whom, which product (sku), how many packs, the price of one pack, and how many days the delivery took against the two days promised. The products table says how much one pack holds: Hilal Dairy sells 12-litre cartons, Tala Farms 10-litre crates.

2. Tidy data and column types

A table is tidy when each row is one observation (here, one delivery), each column is one variable, and each cell holds one value. Tidy tables are what pandas, SQL and every chart expect.

The first check is always the type of each column:

purchase_id object date object branch object supplier object sku object packs int64 pack_price object promised_days int64 delivery_days float64 dtype: object

date, branch, supplier and pack_price are object: pandas stored them as text. For names that is right. For pack_price it is a problem, because text cannot be averaged. Worse, adding text glues it together instead of failing:

['75.76', 'SAR 367.30', '77.96']
sum of the first three prices: 75.76SAR 367.3077.96

That “sum” is three prices glued into one string. A column that should be numeric but is object is the first sign of messy data.

3. Cleaning labels

How many branches does Qahwa House have?

branch University 101 Corniche 95 Olaya 88 Al Faisaliyah 80 Al-Faisaliyah 44 corniche 38 al faisaliyah 35 Univ. 33 olaya 30 university 28 Corniche (Jeddah) 27 OLAYA 24 Olaya Branch 21 Name: count, dtype: int64

Four branches, written thirteen ways: extra spaces, capitals, “Olaya Branch”, “Univ.”. Grouping by this column would split each branch’s deliveries over several groups. The fix has three steps: remove spaces at the ends (strip), use one case (lower), and map the remaining variants to one name.

{'Al Faisaliyah': 156, 'Corniche': 156, 'Olaya': 156, 'University': 156}
{'Tala Farms': 208, 'Hilal Dairy': 208, 'Sarawat Roasters': 104, 'Bunn Roasters': 104}

Always look at value_counts() after cleaning, not only before: a mapping with a typo leaves a fifth “branch” behind.

4. Numbers and dates stored as text

Prices were typed as 52.80, SAR 52.80 or 52.80 SAR. Remove the currency, then convert with pd.to_numeric(..., errors="coerce"), which turns anything it cannot read into a missing value (NaN). Then check that the only missing values are the ones that really were empty:

missing prices before: 24 | after: 24

The counts agree, so no price was lost in the conversion. Had we skipped the replace, every price written with “SAR” would have become NaN silently.

Dates are trickier. 04/03/2025 is the 4th of March in Saudi Arabia and most of the world, but the 3rd of April in the United States. Our staff write the day first, so we say so:

2025-01-06 to 2025-12-31
{1: 48, 2: 48, 3: 54, 4: 52, 5: 54, 6: 50, 7: 51, 8: 53, 9: 55, 10: 55, 11: 49, 12: 55}
Saturday deliveries, day first: 0 | month first: 12

Read day-first, no delivery falls on a Saturday; read month-first, twelve do. Checks that come from knowledge of the business are the strongest ones.

Every date falls in 2025 and every month has deliveries. But a wrong dayfirst would pass these checks too: pandas does not fail, it silently reads 04/03 as the 3rd of April. To catch it, test the dates against something you know about the business. Qahwa House’s suppliers deliver from Sunday to Friday, never on a Saturday:

5. Duplicates

The same delivery can be typed twice, for example when a complaint form is re-entered. An exact duplicate is a row identical to an earlier one in every column, the purchase number included:

20 exact duplicates
sku HIL-M12 16 BUN-K1 2 SAR-K5 2 Name: count, dtype: int64

Most duplicates are Hilal’s milk deliveries, and they are not random ones: they are late deliveries entered a second time. Left in, they make Hilal look less reliable than it is. We removed them at the start of section 3 with drop_duplicates().

6. Missing values

Count what is missing in each column:

purchase_id 0 date 0 branch 0 supplier 0 sku 0 packs 0 pack_price 24 promised_days 0 delivery_days 18 dtype: int64

There are three honest ways to handle a missing value, and the right one depends on the question:

StrategyWhen it fitsRisk
Drop the rowfew values missing, missing for reasons unrelated to the answerlosing data, bias if the missing rows are special
Fill it (median, a value from another source)a sensible value existsinventing data, hiding uncertainty
Flag it (keep a column saying “was missing”)the fact that it is missing may itself matternone, but every analysis must decide again

Before dropping, check whether the missing values are spread evenly. If one supplier’s prices were missing far more often, dropping rows would bias the comparison:

supplier Bunn Roasters 0.038 Hilal Dairy 0.034 Sarawat Roasters 0.029 Tala Farms 0.048 Name: pack_price, dtype: float64

Prices are missing at similar, small rates for every supplier, so for the cost comparison we can drop rows without a price. For the delivery comparison we keep those rows, because their delivery time is known. Each question uses all the data that is valid for it.

7. Outliers: error or real extreme?

The IQR rule flags values far from the middle half of the data. With Q1Q_1 and Q3Q_3 the first and third quartiles and IQR=Q3−Q1\text{IQR} = Q_3 - Q_1, a value is flagged when it lies below Q1−1.5 IQRQ_1 - 1.5\,\text{IQR} or above Q3+1.5 IQRQ_3 + 1.5\,\text{IQR}.

Q1 = 52.31, Q3 = 53.23, fences 50.93 to 54.61 SAR
flagged: [54.78, 54.96, 55.02, 526.2, 527.4]
<Figure size 700x240 with 1 Axes>

The rule flags five prices. It cannot tell you what they are; you must judge each one:

  • 526.2 and 527.4 SAR are impossible for a 12-litre carton that otherwise costs about 53 SAR. They are typing errors (a decimal point lost). We remove them; we could also correct them, if the paper invoice confirmed the true value.

  • The other three (about 55 SAR) are ordinary price variation, just above a narrow fence. They stay.

Not every extreme is an error. Olaya once ordered 75 cartons, nine times the usual amount:

Loading...

That order was placed in early March 2025, during Ramadan, when evening traffic jumps. It is real, so it stays: deleting it would make the data less true, not more. Remove errors; keep real extremes, and write down which you did.

622 deliveries after removing duplicates and the two price errors

8. Joining tables

A Hilal carton costs about 52.80 SAR and a Tala crate about 47.50 SAR, but the packs hold different amounts. The comparison that matters is the price per litre, and the litres per pack live in the products table. We join the two tables on their shared key, sku:

622 rows before the join, 622 after; products not found: 0
Loading...

Two checks follow every join. The number of rows must not change when each delivery matches exactly one product (validate="many_to_one" stops with an error if a key were repeated in products), and no row may fail to find its product. A left join keeps every delivery even when its product is unknown, so failures show up as missing values instead of vanishing.

9. The same question in SQL

SQL is the language of databases, and most company data lives in one. DuckDB runs SQL directly on pandas DataFrames, so you can use whichever is clearer for the question:

Loading...

AVG ignores missing prices, just as pandas does. The same summary in pandas:

Loading...

10. What the cleaning changed

Here is the “quick” analysis someone might do on the raw file: convert the price column as it is, and compare pack prices and late deliveries by product code.

Loading...

The quick analysis says Tala Farms is cheaper and more reliable. It is wrong on both counts:

  • it compares packs of different sizes, half the prices were not read at all (every one written with “SAR”), and two typos inflate Hilal’s average;

  • Hilal’s late deliveries are counted twice.

Cleaned and joined, Hilal Dairy costs about 4.40 SAR a litre against 4.76 for Tala, and is late 7.8% of the time against 9.6%. The same data, wrangled honestly, reverses the decision.

Check your understanding

  1. A column of prices has type object. Name two things that could cause this.

  2. Why is errors="coerce" dangerous if you do not count missing values before and after?

  3. What does 04/03/2025 mean in a file typed in Riyadh, and how do you tell pandas?

  4. When is dropping rows with a missing value a bad idea?

  5. The IQR rule flags a delivery of 75 cartons. Should you remove it?

  6. A join turned 412 rows into 430. What happened?

Answers. 1. Text mixed into the numbers (“SAR 52.80”, “n/a”), or a decimal comma. 2. It turns unreadable values into NaN without telling you, so real prices can disappear. 3. The 4th of March; pd.to_datetime(..., dayfirst=True). 4. When the missing rows differ from the others, for example if one supplier’s prices are missing much more often. 5. Not without checking: here it was a real Ramadan order, so it stays. 6. A key was repeated in the right-hand table, so some rows matched twice; validate="many_to_one" catches this.