Data Cleaning & Preparation
Topic 5 of 14 · In Data Analysis · September 8, 2026
Turn messy, inconsistent exports into trustworthy analysis-ready data: profiling, missing values, duplicates, standardization and reproducible cleaning pipelines.
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:
- How many rows and columns, and what does one row mean (the grain)?
- Which columns exist and what type is each (number, date, text)?
- How many nulls per column and what fraction of the rows do they cover?
- How many duplicates, exact and partial?
- What are the min/max/typical values per numeric column?
- 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?).
| Strategy | Use when | Warning |
|---|---|---|
| Flag it | Missingness itself is meaningful "did not answer" | Adds a column; doubles your work downstream |
| Drop the row | Few rows missing and the column matters | Silently shrinking the sample biases results |
| Drop the column | Column is >50% missing and not critical | You may lose explanatory power |
| Fill a default/zero | Missing means "zero activity" (no orders yet) | Mistaking "unknown" for "zero" |
| Fill a central value | Only as an imputation step for modeling | Reduces 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: =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_idtwice, 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-04stored 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 (ExcelLOWER, SQLLOWER()) 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:
- Raw — source files untouched, archived (your Excel "Raw" sheet)
- Clean — one repeatable transform (Power Query steps, SQL views/CTEs, or a Python script) that turns raw into tidy output
- 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:
- Profile it: rows, columns, nulls %, duplicates, min/max per numeric column, distinct values per categorical column.
- Fix missing values in the least destructive sensible way and log the choice.
- Define the unique key; remove true duplicates with it, investigate key duplicates.
- Standardize case/trim/spacing, convert dates and numbers to true types, map categories to one canonical label.
- Write 5 validation rules and count how many rows violate each.
- Flag outliers with the IQR rule and classify each as error or genuine.
- 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
Rescuing a merged regional export
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
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.
Task 1
Task 2
Task 3
Task 4
Task 5
| Deliverable | Proves |
|---|---|
| Data profile | Survey-before-touch habit |
| Repeatable pipeline | Reproducible cleaning |
| Data dictionary | Column-level documentation |
| Transformation log | Auditable decisions |
| Quality summary | Honest 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
| Term | Meaning |
|---|---|
| profiling | A quick survey of a dataset before fixing anything: row and column counts, grain, nulls, duplicates, value ranges and distinct values. |
| unique key | The column, or combination of columns, that makes each row unique — which must be agreed before you can talk about duplicates. |
| imputation | Filling a missing value with an estimated or default value, never done silently because it disguises how much is actually unknown. |
| data dictionary | A one-line-per-column record — name, type, meaning, allowed values and unit — that explains what a dataset actually means. |
| transformation log | A written diary of every cleaning change, with what changed, why and for how many rows, so the work can be audited. |
| ETL | Extract, Transform, Load: the formal name for moving data from source systems through cleaning into a warehouse ready for analysis. |
Learning Resources
Power Query Documentation (Microsoft)
Official reference for every Power Query transform — the engine behind repeatable cleaning.
Kaggle — Data Cleaning Course
A free, quick hands-on course practicing missing values, scaling and parsing with real datasets.
pandas — Working with Missing Data
Official pandas guide to null handling: dropna, fillna, interpolation and before/after checks.
OpenRefine
A free desktop tool for fast, visual data cleaning — perfect for one-off messy exports.
Real Python — Explore Your Dataset with pandas
A practical walkthrough of profiling a raw dataset before analysis.
What Is Data Cleaning? (Built In)
A clear overview of why cleaning is most of the job and how teams structure it.
Chapter Quiz
Chapter Quiz — Data Cleaning & Preparation
Profile, then fix deliberately: missingness, duplicates, standardization, validation and reproducible pipelines.
Question 1 of 5
What share of a data analyst's job is typically data cleaning and preparation?
Knowledge Check
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.