Mohamed A. Adel.

Data Cleaning & Preparation

Topic 5 of 14 · In Data Analysis · September 8, 2026

⏱ 1–2 WeeksBeginner–Intermediate

Turn messy, inconsistent exports into trustworthy analysis-ready data: profiling, missing values, duplicates, standardization and reproducible cleaning pipelines.

++++FREE LEARNING PATHDATA ANALYSISDATA ANALYSIS · PHASE 2 · INTERMEDIATEDATA CLEANING &PREPARATIONTurn messy, inconsistent exports into trustworthy a…· 2 / 3BEGINNER–INTERMEDIATE1–2 WEEKSmotif / scrub→rawclean3423 · 23 · MODULE 4.3

Overview

Real-world data does not arrive clean. It arrives with empty cells, duplicates, "Cairo" written four different ways, dates as text, and impossibly negative quantities. Cleaning that chaos is the largest slice of a data analyst's work — most estimates put it at 60–80% of the job — and it is also where analyses are won or lost.

This topic gives you one repeatable workflow instead of a bag of tricks: profile → clean → verify → document. You will apply it in Excel and SQL (the tools you already know) using Power Query and repeatable queries, so your cleaning survives new data arriving next week. The same concepts return later in Python and Power BI — once you have the framework, only the buttons change.

Before You Start

  • Complete Basics, Excel and SQL first, because you will be cleaning in exactly those tools.
  • Reuse the deliberately dirty CSV from your Excel practice, which carries nulls, duplicate rows, mixed date formats and stray spaces.
  • Open Power Query (or your SQL sandbox) and confirm you can record steps that replay against a fresh file.
  • Refresh the uniqueness idea from Basics: be able to state the six quality dimensions from memory before touching any data.
  • Prepare a one-page log sheet to capture profiling numbers and every transformation decision as you make it.

Learning Objectives

  • Explain why cleaning is the most time-consuming and most valuable analysis step
  • Profile a dataset before touching it: row counts, columns, nulls, duplicates, value ranges
  • Diagnose and handle missing values by type, and pick drop vs fill vs flag deliberately
  • Remove exact duplicates and understand when near-duplicates are actually distinct
  • Standardize data types, dates, text case, categories and units
  • Validate values against expected ranges and cross-field rules
  • Distinguish genuine outliers from impossible entries and decide with evidence
  • Build a raw → clean → report pipeline that is reproducible when new data arrives
  • Keep a data dictionary and a transformation log that others can audit
  • Produce a short data-quality report alongside any cleaned dataset

Prerequisites

Complete Basics, Excel and SQL — you will clean in those tools. A spread of statistics terms (outliers, skew) helps but is not required yet.

Why Cleaning Is the Real Job

Every claim you make later is built on this step. A missing regional flag silently underweights that region; a duplicated order inflates revenue; a "text" date column breaks every month-over-month comparison. Garbage in, garbage out is not a joke — it is the reason managers stop trusting analytics.

Think of cleaning as journalism for numbers: you are establishing that each row means what it appears to mean before anyone reports it. The good news: a structured workflow makes the process fast and auditable instead of a nightly scramble.

Profile Before You Touch

Profiling is a quick survey of the data before you fix anything. You want answers to six questions:

  1. How many rows and columns, and what does one row mean (the grain)?
  2. Which columns exist and what type is each (number, date, text)?
  3. How many nulls per column and what fraction of the rows do they cover?
  4. How many duplicates, exact and partial?
  5. What are the min/max/typical values per numeric column?
  6. How many distinct values does each categorical column have?

In Excel: a quick Table + filter dropdown + COUNTIFS/COUNTBLANK answers most of this. In SQL, a one-query overview does it:

SELECT
  COUNT(*)                   AS total_rows,
  COUNT(customer_name)       AS name_filled,
  COUNT(DISTINCT customer_id) AS distinct_customers,
  COUNT(DISTINCT region)     AS regions,
  MIN(order_date)            AS first_order,
  MAX(order_date)            AS last_order,
  SUM(CASE WHEN amount < 0 THEN 1 ELSE 0 END) AS negative_amounts
FROM orders;

Profiling first means you fix real problems in priority order, and you know your data's limitations before you defend a conclusion.

Handling Missing Values

Missingness is not random: rows usually go blank for a reason, and that reason can bias your result. Before fixing, ask three things: how much is missing (1% or 40%?), why (not collected? failed import? only applies to some segments?), and does missingness correlate with the variable you care about (richer customers leave the income field blank?).

StrategyUse whenWarning
Flag itMissingness itself is meaningful "did not answer"Adds a column; doubles your work downstream
Drop the rowFew rows missing and the column mattersSilently shrinking the sample biases results
Drop the columnColumn is >50% missing and not criticalYou may lose explanatory power
Fill a default/zeroMissing means "zero activity" (no orders yet)Mistaking "unknown" for "zero"
Fill a central valueOnly as an imputation step for modelingReduces variance; state it clearly

The professional habit: never silently choose. Whatever you do, record it in your transformation log so reviewers see the decision and can challenge it.

Excel / SQL patterntext
Excel:  =IF(ISBLANK(B2), "<no value>", B2)

SQL:    SELECT COALESCE(region, 'UNK') AS region_flagged
        FROM   orders;

Duplicates and Near-Duplicates

Two identical rows are an error unless the row type allows repeats (two same-sized orders from the same customer are legal). The decision rule: first define the unique key — the column set that makes a row unique (e.g. order_id) — then check duplicates on the key.

  • Exact duplicates: every column identical. Almost always an import artifact — remove and log.
  • Key duplicates: same order_id twice, different amounts. Do not delete blindly — investigate which record is the true one.
  • Near-duplicates: "New York" and "new york" and "NY". Those are standardization problems (next section) more than duplicates.

In Excel use Remove Duplicates only after confirming the key. In SQL: SELECT key, COUNT(*) … GROUP BY key HAVING COUNT(*) > 1 shows the suspects before you touch anything.

Types, Formats and Standardization

Consistency is the quiet superpower of clean data. Standardize four things:

  • Types — dates as dates, numbers as numbers. "1,234.56" with a thousand separator, or 2026-09-04 stored as text, breaks every aggregation. Make the type real (Excel: Text-to-Columns / unformatted cell; SQL: CAST(x AS date)).
  • Text case — TRIM, then normalize case (Excel LOWER, SQL LOWER()) so joins and filters match.
  • Categories — one canonical label per value. Map "BI" to "Business Intelligence", "bI", "Bi" to the same thing, and record the mapping so it is repeatable.
  • Units and scales — revenue in USD everywhere, time in the same timezone, percentages stored consistently (0.05 vs 5%).

Build a lookup table for canonical categories instead of editing strings one cell at a time — it is faster, documentable, and reusable for next month's export.

Invalid and Impossible Values

Beyond format, check meaning. A value can be clean-looking yet impossible:

  • Range rules — negative quantity, price above a sane cap, age > 120
  • Cross-field rules — shipped_date < order_date, end_date < start_date, subtotal ≠ sum of line items
  • Completeness rules — an order with no customer, a payment with no amount

These checks are exactly what a data validation layer exists for. In Excel, conditional formatting + data validation lists catch them visually; in SQL, WHERE amount < 0 or a CHECK-style filter surfaces them fast. Write the rules before analyzing so you catch problems on day one, not after you have charted garbage.

Outliers vs Errors

An extreme value is not automatically wrong — a whale account ordering 10,000 units is real. The rule from your statistics topic applies here with extra force: detect → investigate → decide.

After detecting (IQR fence or a sorted scan), ask the data: could a typo have created this? (a 1,000,000 instead of 10,000), is it within the real business range?, does it match the source system? Only then choose: fix the typo, keep-and-flag the legit giant, or exclude with a documented reason. The moment you silently delete a suspicious row, you have decided on someone's behalf — and that is where auditors look first.

The Reproducible Pipeline: Raw → Clean → Report

Clean data is a process, not a one-time edit. Companies formalize this as ETL / ELT — Extract, Transform, Load — moving data from source systems into a warehouse ready for analysis. You build the same shape at your scale:

  1. Raw — source files untouched, archived (your Excel "Raw" sheet)
  2. Clean — one repeatable transform (Power Query steps, SQL views/CTEs, or a Python script) that turns raw into tidy output
  3. Report — the analysis layer reads only the clean step, never the raw chaos

Power Query (Excel/Power BI) records every click as a step you can re-run on new files; SQL puts cleaning into CREATE VIEWs. The payoff: next month's file reprocesses in minutes, and your cleaning logic is version-controlled evidence — a professional artifact, not a mysterious spreadsheet you "fixed" by hand.

Documenting Data Quality

A cleaned dataset is only as trustworthy as its backstory. Deliver two companions with any important dataset:

  • Data dictionary — one line per column: name, type, meaning, allowed values, unit
  • Transformation log — what you changed and why: "removed 3 exact-duplicate rows; filled region='UNK' for 12 nulls; changed 9 dates from text to date"

This turns your work from "a file" into evidence. When a manager asks "wait, where did this number come from?" — and they will — you can answer precisely instead of hoping.

Hands-On Practice

Reuse any messy CSV you can find (or deliberately dirty a clean one: delete cells, repeat rows, mix date formats, add a " new york " row). Complete:

  1. Profile it: rows, columns, nulls %, duplicates, min/max per numeric column, distinct values per categorical column.
  2. Fix missing values in the least destructive sensible way and log the choice.
  3. Define the unique key; remove true duplicates with it, investigate key duplicates.
  4. Standardize case/trim/spacing, convert dates and numbers to true types, map categories to one canonical label.
  5. Write 5 validation rules and count how many rows violate each.
  6. Flag outliers with the IQR rule and classify each as error or genuine.
  7. Assemble the clean dataset in Power Query (reproducible steps) and write a one-page quality report.

Do all profiling by hand in Excel first so you know what the answers look like, then write the same overview as SQL queries. Handle missing values and duplicates with a written decision per column.

Deeper Worked Examples

These examples push further than the core content — each one is a complete, step-by-step solution you can follow and then reproduce on your own.

Rescuing a merged regional export

Problem. The finance team merged three regional exports into one workbook of 1,200 rows and apologised with 'there are a few issues'. Profiling shows four exact duplicate rows, nine duplicate order_id values with different amounts, region written as 'cairo', 'CAIRO' and 'Cairo', twelve rows with no customer email, one amount of -40, and order dates stored partly as text such as '04-09-2026'.
1

Step 1

Profile before touching anything: record 1,200 rows, the null and duplicate counts, the minimum and maximum amounts and the distinct region labels, and write these results at the top of your transformation log.
2

Step 2

Define the unique key — order_id plus a line number if one order can hold several lines — then run SELECT order_id, COUNT(*) FROM merged GROUP BY order_id HAVING COUNT(*) IN (2, 3, 4) to list the exact suspects rather than guessing.
3

Step 3

Investigate the nine key duplicates against the source exports and keep the record that matches the source signature; remove only the four fully identical rows and log both counts.
4

Step 4

Standardise the region column to one canonical label: trim whitespace, lower-case everything, then map 'cairo', 'CAIRO' and 'Cairo' all to 'Cairo', and count the corrected rows.
5

Step 5

Handle the twelve missing emails deliberately by filling them with a neutral 'no_email' flag column rather than deleting rows, and record that decision with its reason.
6

Step 6

Convert the mixed date formats to genuine dates, then validate the negative amount against the refund policy before deciding whether it is impossible or a legitimate credit.
7

Step 7

Re-profile the clean output: confirm zero exact duplicates, one region label and no negative amounts, then write the one-page quality report and the transformation log for the finance team.

Common Mistakes

  • Deleting rows silently — always log why, or reviewers will re-litigate your numbers
  • Filling every missing value with zero and mistaking 'unknown' for 'none'
  • Removing duplicates without first defining the unique key
  • Comparing non-standardized text ('NY' vs 'New York') and getting misleading counts
  • Leaving dates and numbers as text and wondering why sorting/grouping breaks
  • Checking format but not meaning (a clean negative quantity is still impossible)
  • Editing the raw file directly instead of building a repeatable clean step
  • Cleaning without a data dictionary, so next month's version re-invents the rules

Real-World Usage

Hiring managers test cleaning judgement because every real project starts in the mud: split systems, one-off exports, fields named differently from one department to the next. The analysts who stand out are the ones who can look at a messy file and describe — in one minute, with a profile — what is wrong and what they will do about it. Later in this path your Power BI model and Python analyses both consume this pipeline: build it once, reuse it everywhere.

Mini Project

Business problem: The finance team merged three regional exports into one spreadsheet and handed it to you with the note "there's a few issues".

Dataset: any 300+ row sales file (superstore-style) that you deliberately break: 5% nulls, ~10 duplicate rows, mixed date formats, inconsistent category labels, 2–3 out-of-range amounts, 1–2 negative quantities.

Objective: deliver a clean, reproducible, documented dataset and let someone else verify your choices.

1

Task 1

Write a one-page profile (grain, counts, nulls, duplicates, value ranges, issues list).
2

Task 2

Build the cleaning steps in Power Query (or SQL views) from a raw copy — no manual edits to the source.
3

Task 3

Produce the clean output plus the data dictionary.
4

Task 4

Produce the transformation log itemizing every fix and rationale.
5

Task 5

Write a 3-line quality summary: what is now trustworthy, and what is still unknown.
DeliverableProves
Data profileSurvey-before-touch habit
Repeatable pipelineReproducible cleaning
Data dictionaryColumn-level documentation
Transformation logAuditable decisions
Quality summaryHonest limits of the data

Key Takeaways

  • Cleaning is 60–80% of analysis — budget for it and make it auditable
  • Profile first: grain, counts, nulls, duplicates, ranges, distinct values
  • Choose missing-value handling deliberately; never silently drop or zero-fill
  • Define the unique key before touching duplicates
  • Standardize types, case, categories and units to one canonical form
  • Validate meaning, not just format — impossible values fail range/cross-field rules
  • Outliers: detect → investigate → decide, and document
  • Build Raw → Clean → Report pipelines so next month's file reprocesses itself
  • Ship a data dictionary and transformation log with important datasets

Key Terms & Glossary

The vocabulary this topic uses, defined the way a working professional would.
TermMeaning
profilingA quick survey of a dataset before fixing anything: row and column counts, grain, nulls, duplicates, value ranges and distinct values.
unique keyThe column, or combination of columns, that makes each row unique — which must be agreed before you can talk about duplicates.
imputationFilling a missing value with an estimated or default value, never done silently because it disguises how much is actually unknown.
data dictionaryA one-line-per-column record — name, type, meaning, allowed values and unit — that explains what a dataset actually means.
transformation logA written diary of every cleaning change, with what changed, why and for how many rows, so the work can be audited.
ETLExtract, Transform, Load: the formal name for moving data from source systems through cleaning into a warehouse ready for analysis.

Learning Resources

These curated sources go deeper than this module: official docs, books, interactive practice, and full courses. Mix them into your routine to go from comfortable to professional.

Power Query Documentation (Microsoft)

Official reference for every Power Query transform — the engine behind repeatable cleaning.

Open resource ↗

Kaggle — Data Cleaning Course

A free, quick hands-on course practicing missing values, scaling and parsing with real datasets.

Open resource ↗

pandas — Working with Missing Data

Official pandas guide to null handling: dropna, fillna, interpolation and before/after checks.

Open resource ↗

OpenRefine

A free desktop tool for fast, visual data cleaning — perfect for one-off messy exports.

Open resource ↗

Real Python — Explore Your Dataset with pandas

A practical walkthrough of profiling a raw dataset before analysis.

Open resource ↗

What Is Data Cleaning? (Built In)

A clear overview of why cleaning is most of the job and how teams structure it.

Open resource ↗

Chapter Quiz

Put this lesson to work: answer the questions below, get instant feedback and a pass/fail score. Score 70% or higher before you move on — that is your gate to the next topic.

Chapter Quiz — Data Cleaning & Preparation

Profile, then fix deliberately: missingness, duplicates, standardization, validation and reproducible pipelines.

0 / 5

Question 1 of 5

What share of a data analyst's job is typically data cleaning and preparation?

Knowledge Check

Decide how the column is used: if region drives every report, fill/flag strategically (e.g. 'UNK' bucket) and tell stakeholders; if it is rarely used, drop it. Never silently delete the rows — 45% missing would shred your sample.
Investigate before deleting: pull the source to find the true amount (or whether one is a correction), then keep the verified record and log the removal. Deleting by same-key alone can erase a real correction.
Because 'well formatted' is not 'valid' — a negative quantity is impossible for your business rule, so it needs investigation (refund? data-entry error?) rather than trust.
The transform is encoded as repeatable steps — Power Query operations, SQL views, or a script — that re-run on new raw files and produce the same logic, instead of you hand-editing cells each time.
A record of every change (what, why, how many rows) made while cleaning. It lets reviewers audit your decisions and lets you answer 'where did this number come from?' precisely.

End-of-Topic Exam

Hint: How is the column used, and what would deleting rows do?

Model answer: Because region drives every regional report, I would fill the nulls with a visible 'UNK' value plus a flag column, keep the rows, and tell stakeholders that regional splits under-count these records. I rejected silently deleting the rows because 45% of the sample would vanish and every regional comparison would become biased.

Hint: Investigate before deleting — duplicates only look indistinguishable.

Model answer: One: confirm order_id really is the unique key. Two: pull both records and their source signatures — which export, which timestamp, who entered each. Three: decide which is the true record, possibly a correction, and keep it. Four: archive the other row and log the decision with its evidence. Never delete by key alone.

Hint: Format can be fine while meaning is wrong.

Model answer: Because validity is about meaning, not formatting: a negative quantity is impossible for a plain sales rule, so it must be investigated. It could legitimately be a refund or credit note, in which case it is valid once marked as such, or a data-entry error that must be corrected. Clean formatting alone is never proof that a value is acceptable.

Hint: Documentation turns a file into evidence.

Model answer: Ship a data dictionary (column-by-column type, meaning and allowed values), a transformation log (every change, with why and how many rows), and a short quality report (what is trustworthy and what is still unknown). For the finance manager these matter because when anyone asks where a number came from, the documentation answers precisely instead of relying on memory.

Next Step

Congratulations — you just finished Data Cleaning & Preparation. The next topic is Power BI. Press on when you are ready: it will build directly on what you practiced here.