How to Clean Messy Data in Excel and Google Sheets

A student downloads 250 fictional learning-resource sessions to investigate how learners use videos, quizzes, worksheets and articles. At first, the spreadsheet looks organized: every column has a name, the dates appear to describe one year, and most durations are numbers. But “Biolgy” sits beside “Biology”; some text contains invisible characters; a few session IDs repeat; and one date could mean either April 5 or May 4. If the student immediately creates a chart, that chart may look convincing while counting invalid or duplicated evidence.

This data cleaning in Excel and Google Sheets tutorial takes the reader from first inspection to an auditable, analysis-ready dataset. Unlike a formula glossary, it explains the full reasoning cycle: Problem → Cause → Detection → Cleaning Method → Verified Result → Validation → Student Exercise. Each step distinguishes a reversible change from a judgment that must wait for evidence. It is designed for international high school students, university beginners, researchers and future data analysts.

Verified fictional project: 250 source rows; 234 accepted after documented rules; 16 quarantined for unresolved validity issues or exact-copy removal; 19 accepted rows changed by known corrections; 215 accepted rows unchanged. 250 = 234 + 16. The source CSV remains available. The audit register contains 37 deliberately inserted issue events, and an issue event is not necessarily the same as a distinct affected record.

By the end, you will know how to identify misleading duplicate matches, repair ordinary and nonbreaking spaces, standardize controlled categories, convert numeric text, handle locale-sensitive dates, validate lookup keys, investigate outliers, design Power Query steps, use Google Sheets regex tools and defend your final cleaning report. You will also complete 20 exercises with model answers and a ten-stage capstone.

The repeatable data-quality workflow
1. Raw source2. Profile3. Detect4. Investigate5. Transform6. Validate7. Document

Raw data are preserved; unresolved records remain visible in the review queue.

What is data cleaning? Six related terms explained

Data cleaning is the investigation and appropriate correction, preservation, exclusion or flagging of data-quality problems so that recorded information can answer a stated question. It does not require every field to be filled or every value to fit a narrow range. A student who changes an unknown score into an invented average may make a worksheet look tidy while damaging its scientific integrity.

TermPrimary purposeExample
Data profilingFind distributions, data types, gaps and anomalies before editingCount blank ratings and duplicate IDs
Data cleaningCorrect or handle documented errors and inconsistenciesMap approved label Bio to Biology
Data standardizationApply a consistent defined representationStore all valid sessions in ISO date representation
Data transformationChange structure or representation for analysisConvert validated numeric text into numeric cells
Data validationCheck data against explicit requirementsConfirm each accepted Rating is 1–5 or blank
PreprocessingPrepare inputs for later analysis or modelsEncode categories after quality checks

The boundaries overlap. A conversion from text “45” to the number 45 is a transformation and can also be a cleaning action. Creating a one-hot encoded column may be preprocessing but need not be cleaning. What matters is that you can describe the reason for an action and test its consequences.

Why data quality matters: seven dimensions

An accidental duplicate inflates the number of sessions. A negative duration depresses the mean. A blank duration interpreted as zero makes real study times look shorter. Inconsistent category labels break grouped summaries, and date strings stored as text can sort alphabetically rather than chronologically. A missing ResourceID match creates orphaned records that silently disappear from inner-join summaries. These errors become especially costly when a dashboard, scientific report or machine learning model uses the affected output.

Quality is multidimensional. Accuracy asks whether a record represents what actually happened; consistency asks whether the same concept uses the same representation; completeness measures information present; validity checks permitted formats or ranges; uniqueness checks the defined observation key; reliability concerns trustworthy collection; and reproducibility means another analyst can regenerate the result. A dataset can pass a simple validity rule and still be unrepresentative or biased.

Meet the Global Student Learning Resources dataset

Our entirely fictional dataset contains 250 source records distributed across a single synthetic year. The central unit is one learning-resource session, not one learner. This distinction is essential: the same learner can legitimately use one resource more than once, and such rows should not be removed merely because learner and resource codes repeat. The original export is deliberately noisy and its issue-injection register documents what was changed for teaching purposes.

ColumnMeaning and typeValidation rule
SessionIDText identifier for one sessionNonempty and unique; conflicting duplicates require investigation
LearnerCodeFictional five-character learner IDPreserve leading zeros as text
ResourceIDFictional resource keyMust match documented R0001–R0024 lookup
SessionDateDate of activityReal, unambiguous calendar date
StudyLevelHigh school or UniversityApproved category only
RegionBroad fictional region labelOne of six documented values
SubjectSchool subjectOne of six standardized subjects
ResourceTypeVideo, Article, Quiz or WorksheetApproved category only
MinutesSpentDuration in minutesNumeric and nonnegative; >600 flagged for review
CompletedCompletion status0 or 1
RatingOptional learner rating1–5 when provided; blank is allowed
SourceFileOriginating fictional filePreserve provenance text

The documented subject values are Biology, Chemistry, Mathematics, Physics, Computer Science and Geography. The six regions are Africa, Asia, Europe, North America, South America and Oceania. Region here is a harmless synthetic category, not an assertion about a real student’s location. A new category cannot be added by the analyst simply because it resembles an approved label; approval requires a source and a policy decision.

Common messy-data problems and the safest first response

ProblemExampleRiskFirst action
Ordinary spaces“ Biology ”Lookup mismatchInspect and trim
Nonbreaking spaceBiology followed by CHAR(160)Invisible category differenceReplace documented character
Control characterChemistry with vertical tabUnmatched stringInvestigate and apply CLEAN where applicable
Duplicate IDS0097 on two different rowsUncertain event identityQuarantine both pending review
Exact duplicateOne row copied in another importInflated activity countExclude only verified extra copy
Missing required fieldBlank SessionIDUntraceable observationFlag for review
Optional missing valueBlank RatingFalse zero if coercedRetain missing
Numeric text“45”Numeric summary inconsistencyConvert after checking meaning
Decimal comma“3,5”3.5 may be read incorrectlyUse documented source locale
Ambiguous date04/05/2025Wrong month assignmentDo not guess
Outlier9000 minutesDistorted averageInvestigate plausibility
Unknown keyR9999Failed ResourceID lookupFlag unmatched relation

Step 1: Preserve the source and profile it

First, save an untouched source export and record its origin, date, expected row count and column names. Create a separate working copy. In the companion workbooks, Raw_Data holds source observations, Data_Dictionary states field rules, Issue_Register records injected problems, Working_Cleaning documents decisions and Clean_Final holds accepted observations. Other tabs cover README, Quality_Report, Practice, Answer_Key, Validation and Change_Log. Worksheet protection can help prevent accidents, but it is not a confidentiality guarantee; edit permissions and encryption are separate concerns.

Before transforming anything, record the number of rows, missing required fields, candidate duplicate keys, unexpected category spellings, minimum and maximum numerical values, raw date representations and lookup failures. Use filters to scan suspicious values, and separately count missing ratings versus missing study durations. A simple dashboard made before profiling can hide errors behind pleasant colors and plausible averages.

Useful starting formulas

=COUNTA(Raw_Data!L2:L251)\n=COUNTBLANK(Raw_Data!I2:I251)\n=COUNTIF(Raw_Data!$A$2:A2,Raw_Data!A2)>1

Here column L contains SourceFile, populated for all 250 teaching records. COUNTA over SessionID alone would miss the deliberately blank ID, so choosing the denominator matters. COUNTBLANK measures the range and treats some empty-string formula results as blank. The COUNTIF expression flags a later occurrence of an ID; it does not prove two rows are redundant. Explicitly review the underlying records before removing anything. Microsoft Power Query also offers Column quality, Column distribution and Column profile features to supplement basic formulas.

The project’s baseline is 250 rows, 12 columns and 37 explicitly recorded injected issue events across 37 source rows. These counts describe the designed teaching dataset, not a universal benchmark or a quality score. After cleaning, preserve a ledger of unresolved records rather than making them disappear from the evidence trail.

Step 2: Remove extra spaces without losing meaningful text

Ordinary leading and trailing spaces create different text values even when the displayed label looks identical. Multiple internal spaces can break equality checks and lookup keys. In both Excel and Google Sheets, TRIM removes ordinary leading and trailing spaces and reduces repeated ordinary spaces between words. It should be applied to controlled text labels, not indiscriminately to every text field. For example, codes may encode separators intentionally, and legal names require more cautious handling.

=TRIM(A2)
Before textCleaning methodAfter textWhat changed
“ Biology ”TRIM“Biology”Removes ordinary boundary spaces
“Computer Science”TRIM“Computer Science”Collapses repeated ordinary internal spaces
“Biology” + nonbreaking spaceTRIM aloneNot reliably cleanedCHAR(160) needs separate handling

The third example explains a common surprise. A nonbreaking space, U+00A0, often enters data through a webpage or copy-and-paste process. Excel’s ordinary TRIM is designed around the ASCII space character, so this character may remain. The companion source records intentionally contain one such value, distinct from an ordinary trailing space.

Safely handle the common nonbreaking space

=TRIM(SUBSTITUTE(A2,CHAR(160)," "))

SUBSTITUTE converts this specific nonbreaking-space character into an ordinary space, then TRIM removes or collapses those ordinary spaces. This is a targeted repair, not a universal Unicode-whitespace scrub. It will not normalize all zero-width marks, directional controls or visually similar characters. Inspect the source code point where the expected category still does not match.

Step 3: Remove supported nonprinting characters

Invisible control characters sometimes arrive in exported files. An ASCII vertical tab can become part of the apparent word “Chemistry” without showing as a normal letter. CLEAN is useful for common nonprinting ASCII characters; it is not a complete Unicode text normalizer. Always investigate first, because a symbol that looks strange might be meaningful in a scientific field or encoded identifier.

=CLEAN(A2)
=TRIM(CLEAN(SUBSTITUTE(A2,CHAR(160)," ")))

The combined formula first targets U+00A0, then removes supported nonprinting characters, then normalizes ordinary spaces. Order matters: if removing a control character causes two valid words to run together, replace that character with a separator rather than deleting it. Our generated CSV contains the true control character; the Excel workbook displays the visible symbol ␋ in that one cell because XML-based XLSX storage cannot contain U+000B. The issue register identifies the source exception.

Step 4: Standardize capitalization and approved categories

Use UPPER, LOWER or PROPER when the target capitalization is known. They make “biology”, “BIOLOGY” and “Biology” comparable; however, they cannot infer that “Bio” and “Biolgy” represent Biology. A robust workflow defines an approved mapping table and uses an exact-match lookup after ordinary text normalization. Never infer an unknown scientific category merely because it resembles a familiar label.

=UPPER(TRIM(A2))
=LOWER(TRIM(A2))
=PROPER(TRIM(A2))
Source labelApproved outputEvidence for mapping
BioBiologyPreapproved fictional alias
BIOLOGYBiologyCase-insensitive exact category match
BiolgyBiologyExplicitly documented fictional typo
ChemChemistryPreapproved fictional alias
AstronomeeNeeds reviewNo approved mapping; not guessed

In Excel, a controlled mapping can use XLOOKUP in compatible versions, with VLOOKUP or INDEX/MATCH as alternatives. Google Sheets also supports lookup functions. Configure the reference table so unmatched entries produce an explicit “Needs review” label rather than silently substituting a default. The fictional dataset maps a short list of known aliases but quarantines the unknown value Astronomee. The purpose is to practice evidence-led standardization, not automatic spelling correction.

Step 5: Investigate duplicates at the observation level

The word “duplicate” can describe at least three different problems. An exact duplicate is an additional copy of the same 12-column source record. A conflicting duplicate identifier uses the same SessionID for different recorded details; deleting either copy arbitrarily could erase a real event. A legitimate repeat occurs when one learner studies the same resource on different sessions, each with its own unique SessionID. The dataset deliberately includes all three so that the correct decision is observable.

=COUNTIF($A$2:A2,A2)>1

In Excel, use Home → Conditional Formatting → Highlight Cells Rules → Duplicate Values for a visual first pass, or Data → Remove Duplicates on a carefully copied dataset only after identifying the precise deduplication key. In Google Sheets, use Data → Data cleanup → Remove duplicates, or UNIQUE to produce a separate distinct result where suitable. Microsoft warns that the Remove Duplicates command removes data, so the raw source must be preserved. Neither application knows automatically whether a repeated learner is actually a repeated session.

SituationDataset illustrationDecision
Later exact import copiesSource rows 250 and 251 repeat earlier complete rowsExclude later copies; record why
Conflicting identifierS0097 appears in source rows 98 and 99 with different valuesQuarantine both until source resolves identity
Legitimate repeated studySame fictional learner and ResourceID; distinct sessionsKeep both observations

A reliable duplicate audit first defines uniqueness, then lists all candidate matches, compares conflicting fields, records a decision for every affected source row and recomputes counts. The accepted dataset retains 234 unique SessionIDs. Because two conflicting rows remain unresolved, they are quarantined rather than forced into one row. This conservative choice sacrifices some completeness to protect validity and traceability; a real project could revisit the records after contacting the responsible data owner.

Step 6: Distinguish blanks, zero and missing information

A blank cell might mean “not yet recorded,” “not applicable,” “value unavailable” or an error introduced during import. A value of zero can be a real measurement. A formula such as ="" returns an empty text string, which may be counted differently across particular functions. Investigate the source and the field definition before choosing a response. In this project, MinutesSpent and Rating are optional, so a genuine blank remains missing and is not converted to zero.

=COUNTBLANK(I2:I251)
=ISBLANK(I2)
=IF(I2="","Missing duration","Recorded duration")

Do not automatically replace all missing durations with the mean: such imputation could underestimate variability and distort comparisons across subject groups. Removing all incomplete rows could also bias the sample if missingness is more common for particular learners or resources. If the research question permits imputation, document the statistical assumption and assess sensitivity. For this beginner teaching project, retaining optional missingness and reporting the number of measured durations is a clearer policy.

Verified result: the accepted 234-row dataset has 1 missing optional duration and 16 missing optional ratings. These are not data-quality failures under the stated dictionary. The duration mean should use the 233 measured durations, not the total of 234 rows as denominator.

Step 7: Convert text numbers safely and preserve IDs

Values that appear numerical are not necessarily stored as numbers. They can be strings, include extra spaces, or use local decimal and grouping separators. In a compatible Excel environment, VALUE parses many recognized numeric strings; NUMBERVALUE allows explicit decimal and grouping symbols. Google Sheets provides VALUE for text in recognized formats and uses its spreadsheet locale. For an ambiguous string such as “1,250”, it is irresponsible to decide whether it means twelve hundred fifty or one and a quarter without knowing the source convention.

=VALUE(TRIM(A2))
=NUMBERVALUE(A2,",",".")

In our fictional source, the meaning of “3,5” is documented as decimal-comma 3.5; “1,250” is explicitly tagged as an English-style grouped 1250-minute value and therefore also triggers an unusually long duration review. These conventions are known because we created the dataset and documented its issue register. Real downloaded data usually require source evidence. To avoid conversion errors, test candidate inputs and check both value and data type.

A learner identifier like 00007 is not seven minutes or seven ratings. Store it as text, preserving all five characters, and do the same for ResourceIDs. Converting lookup keys to numeric values may strip meaningful zeros and disconnect relationships. A data-cleaning system that preserves mathematical values but damages IDs is not successful.

Step 8: Normalize dates without guessing the calendar

Excel and Google Sheets store valid dates internally as date-like numeric values even though they may display differently. A string that looks like a date may still be plain text. Formatting it with a date pattern does not guarantee parsing succeeded. Our source includes ISO dates, “5 Apr 2025”, a known year/month/day representation, one ambiguous slash-formatted date, and one impossible calendar date.

SourceMeaningAction
2025-04-05Explicit ISO 8601 dateAccept as 5 April 2025
5 Apr 2025Text month removes day/month ambiguityParse after checking
2025/04/05Declared YYYY/MM/DD sourceConvert with documented source format
04/05/2025April 5 or May 4Quarantine until verified
2025-02-30Impossible calendar dayQuarantine; do not invent a replacement
=DATE(2025,4,5)
=DATEVALUE(A2)

Use DATE when year, month and day components are known; use DATEVALUE only when a text format can be reliably interpreted under the active locale. Excel Power Query supports Change Type → Using Locale, which is preferable to allowing an unverified automatic date guess. In Google Sheets, inspect File → Settings → Locale and test conversions. A final date column should be validated for calendar reality, expected year and chronological consistency. If the source format remains ambiguous, report that limitation openly.

Step 9: Find invalid numerical values and outliers

A negative study duration is incompatible with the project’s nonnegative measurement rule, while a rating of 6 falls outside the stated optional 1–5 scale. A value of 9000 minutes is extreme but does not prove a typo. For the teaching project we set a conservative review threshold above 600 minutes; values beyond it are quarantined pending evidence, not automatically replaced with an average. Different studies could adopt different thresholds, units and retention rules.

=IF(OR(NOT(ISNUMBER(I2)),I2<0),"Review duration","Candidate valid")
=IF(OR(K2="",AND(ISNUMBER(K2),K2>=1,K2<=5)),"Candidate valid","Review rating")

For outlier screening, calculate the first quartile Q1 and third quartile Q3, then IQR = Q3 − Q1. A common Tukey-style screening rule flags values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR. This method locates observations far from the sample’s middle half; it does not establish a physical or educational impossibility. The mean can be strongly affected by extreme values, so a median and sensitivity comparison may better describe a skewed dataset.

Step 10: Validate lookup keys and relationships

A clean-looking SessionID is not sufficient if the ResourceID does not exist in the approved reference list. For this project, R0001 through R0024 are the only defined resource keys. R9999 has no match. An exact-match lookup can identify the error; neither Excel nor Google Sheets should automatically assign the record to a similar-looking resource. Conflicting IDs should be reviewed across tables as well as within each table.

=IF(COUNTIF(Resource_Lookup!$A$2:$A$25,C2)=0,"Unmatched ResourceID","Matched")

To reproduce this formula, first create a separate Resource_Lookup tab with the 24 approved keys in A2:A25; the companion workbook documents the key domain but the example lookup tab must be created by the student. Alternatively, use the Data Dictionary’s resource-code rule to validate with a controlled key list. An inner join that silently discards unmatched records can make downstream totals appear lower without explanation.

Step 11: Prevent new errors with data validation

After correcting a dataset, design controls that make the same problems less likely to recur. Use dropdowns for Subject, Region, StudyLevel and ResourceType; specify allowed rating values; prohibit negative durations; and provide clear input messages for dates and SessionIDs. Students can still paste invalid values or import unexpected data, so validation is a prevention layer rather than a guarantee of correctness. Periodic profiling and independent post-import checks remain necessary.

In Excel, select an input range and use Data → Data Validation, choosing List, Whole number, Decimal, Date or Custom as appropriate. In Google Sheets, select the editable cells and use Data → Data validation (or Insert → Dropdown for relevant dropdown experiences), then enter allowed options, validation behavior and explanatory help text. Test with valid and invalid examples. A warning that permits invalid entry is different from a rule that rejects it.

Step 12: Excel Power Query — build a repeatable cleaning pipeline

Project: Clean a Messy CSV Dataset in Excel with Power Query. Power Query is Excel’s import and transformation technology. It creates applied steps that can be rerun when a source changes. On supported Windows desktop versions, use Data → Get Data → From File → From Text/CSV and select the raw CSV. Preview the field names, choose Transform Data, and inspect the Power Query Editor rather than loading unexamined text as a final result. Availability and menus differ across Excel versions and platforms, especially on the web and older Mac installations, so verify the installed environment before following a desktop-only step.

The first screen should be an investigation, not a list of automatic deletions. Confirm the imported character encoding and delimiter, then choose View → Column quality, Column distribution and Column profile where available. Power Query’s profile may initially describe only the first thousand rows for performance; use the entire dataset option when the full population needs assessing. Our 250-record exercise fits comfortably within that scale. Look at category variants and error proportions before changing data types.

A reproducible 17-action Power Query walkthrough

ActionWhat to doWhat to verify
1–3Import CSV; choose Transform Data; inspect headers12 columns and 250 source rows
4–6Enable column quality, distribution and profileMissing/invalid candidates recorded
7–9Set text columns explicitly; trim ordinary spaces; clean supported controlsLeading-zero IDs unchanged
10–11Normalize approved categories; inspect duplicate SessionIDsS0097 conflict and two exact later copies identified
12–14Flag invalid durations; parse dates with verified source locale; add DataStatusAmbiguous date remains unresolved
15–16Review Applied Steps; load results to a separate sheetRaw_Data is not overwritten
17Refresh after updating source filesSame rules apply and new exceptions are reported

Before setting numeric types, remember that some rows contain “3,5”, “1,250” or the text “unknown”. A blanket Change Type step will produce errors or misinterpret values without locale metadata. For dates use Change Type → Using Locale, but only for a column or subset whose input convention is known. Filter unexpected categories into a review query; maintain a separate exception table instead of dropping them from the reporting workflow without explanation.

Short executable example in Power Query M

let
    Source = Excel.CurrentWorkbook(){[Name="RawSessions"]}[Content],
    Trimmed = Table.TransformColumns(
        Source,
        {{"Subject", each if _ is text then Text.Trim(Text.Clean(_)) else _, type text}}
    ),
    WithRow = Table.AddIndexColumn(Trimmed, "SourceRow", 2, 1, Int64.Type)
in
    WithRow

This M example runs only after you create an Excel table named RawSessions. It demonstrates simple text cleaning and a source-row index; it is not a complete safe policy for duplicates, missingness or dates. For actual production transformations, add specific mapping and review steps in the editor. Power Query M is a language separate from Excel worksheet formulas; tools such as Text.Trim, Text.Clean, Table.SelectRows and Table.TransformColumnTypes operate on values or tables, not directly on individual spreadsheet cells. A sample .pq file is included with the companion package, but no active Excel Power Query connection is claimed to be embedded in the downloadable workbook.

The central advantage is reproducibility: when a fresh file arrives, the steps can be refreshed and reviewed. The central limitation is that a saved sequence of steps does not prove the underlying decisions are correct. Recheck source paths, privacy permissions, schema changes and date conventions on every import. Use a review queue for anomalies that cannot be resolved deterministically.

Step 13: Google Sheets — clean the same records collaboratively

Project: Clean the Same Messy Dataset Using Google Sheets. Create a new spreadsheet and import the original CSV through File → Import. Choose the appropriate delimiter, preserve the imported source in Raw_Data and copy it to Working_Cleaning before transformations. Review File → Settings for locale. A team member in a different region may read a slash date differently, and formatted output is not proof that source interpretation was correct.

Use Data → Data cleanup → Cleanup suggestions or Column stats when those features are available in the current interface. These suggestions help flag common patterns but cannot know if two sessions are truly redundant. Inspect them before applying. To remove ordinary spaces using the interface, use Data → Data cleanup → Trim whitespace on a copy; use TRIM, CLEAN and SUBSTITUTE formulas for transparent, repeatable formula columns. Some cleanup operations overwrite selected cells, so preserve an independent source tab.

Sheets formulas for a bounded practice range

=TRIM(G2)
=TRIM(SUBSTITUTE(G2,CHAR(160)," "))
=CLEAN(G2)
=REGEXREPLACE(G2," {2,}"," ")
=REGEXMATCH(G2,"^[A-Za-z ]+$")
=IF(COUNTIF($A$2:A2,A2)>1,"Repeated ID","First occurrence")
=IFERROR(VALUE(I2),"Review numeric text")

REGEXREPLACE and REGEXMATCH use the supported RE2 regular-expression engine. The pattern shown collapses repeated ordinary spaces; it does not remove all Unicode whitespace. The REGEXMATCH example recognizes ASCII letters and spaces only, so do not use it as a universal validation rule for international names or languages. IFERROR should reveal a review status rather than disguise a data-conversion failure. SPLIT can divide known compound text fields, while ARRAYFORMULA can apply compatible formulas over a range. However, repeated full-column array calculations can slow large workbooks; choose bounded ranges when possible.

For structured cleaning, create standardized columns alongside raw columns. Copy only validated values into Clean_Final, then lock or restrict editing as appropriate. Native Google Sheets protections guard against accidental edits but do not automatically make shared data private. Check viewer, commenter and editor access. Keep an Issue_Register that can store multiple issues per row and a Change_Log that explains what was changed, why and by whom.

Step 14: Add quality flags without hiding overlapping errors

A single generic “Needs review” label can conceal several failures in one row. For example, a row could have an invalid date and an unknown ResourceID. A robust design uses an issue-level register with one entry per detection, plus a row-level DataStatus summary. Recommended statuses include Valid, Missing required value, Duplicate identifier, Invalid date, Invalid duration, Invalid category, Unmatched ResourceID and Needs review.

In the companion dataset, every injected issue has a known row reference and an intended cleaning decision. The completed workbook’s Working_Cleaning tab records the final accepted or quarantined status and associated blockers. When interpreting the issue event count, do not sum category totals as though each row were unique. Real-world source data often have multiple simultaneous problems, and analysts should preserve all relevant flags even after the row is excluded from the primary analytical table.

Fictional project: count reconciliation
Source rows
250Accepted
234Quarantined
16

Verified counts: 250 = 234 + 16. Source rows are preserved; an issue-event total is not a distinct record total.

Step 15: Create a before-and-after data-quality report

Verified metricRaw / baselineAccepted / outcomeInterpretation
Dataset row count25023416 records quarantined or excluded
Accepted with normalized field(s)Not applicable19Known, documented deterministic corrections
Accepted unchangedNot applicable215No accepted field changes
Unique accepted SessionIDsConflicts and exact duplicates present234Every accepted ID unique
Missing optional MinutesSpentPresent in raw1Valid optional missingness retained
Missing optional RatingPresent in raw16Valid optional missingness retained
Duration above review thresholdTwo known injected examples0 acceptedHeld for source review
Unresolved date cases2 injected source cases0 acceptedAmbiguous/impossible dates not guessed
Unmatched ResourceID1 known injected source case0 acceptedR9999 held for review
Completed sessionsNot compared without normalization15666.67% of 234 accepted records
Total measured minutesUnreliable until cleaning18,982.5233 numeric measured sessions

The accepted mean of measured duration is 81.47 minutes, calculated as 18,982.5 / 233 after preserving the single missing duration. It is not the mean across all 250 source rows and must not be compared with an unfiltered raw mean as though they were equivalent populations. These outcomes are generated from a deliberately controlled fictional dataset; another dataset will yield different values.

The 19 corrected accepted rows are distinct from the 16 quarantined records, so the accepted group reconciles as 234 = 19 changed + 215 unchanged. The raw group reconciles as 250 = 234 accepted + 16 quarantined. This prevents a common reporting error: celebrating fewer invalid values without accounting for rows that were lost. A stronger audit stores the exact source-row reference for every removal or unresolved condition.

Step 16: Independently validate the final dataset

Validation must be separate from the cleaning logic itself. Verify accepted IDs are unique, required fields are present, leading-zero codes remain text, dates are real and unambiguous, categories belong to their allowed lists, ratings stay inside 1–5, durations are nonnegative, and each ResourceID exists in the lookup list. Independently recalculate completion totals, observed duration totals and row counts. Compare source rows to output records using a stable source-row reference, not a sorted row position that may change.

The downloadable Validation tab contains checks for row reconciliation, ID uniqueness, valid ratings, valid duration values, required lookup consistency and preservation of five-character learner codes. The workbook was produced and audited programmatically; these results have not been claimed as independently executed within Microsoft Excel or Google Sheets. If a formula recalculates differently in the reader’s installed software, document the version, locale and discrepancy before making a public numerical claim.

Independent reconciliation: all 234 accepted sessions have unique SessionIDs; there are no accepted negative durations, invalid ratings, unresolved dates, unsupported subjects or unmatched resource identifiers under the stated rules. The quarantined 16 observations remain fully listed for review. The cleaned dataset is fit for the stated practice summaries, not proof that the original fictional measurements are error-free.

Excel versus Google Sheets: choosing the appropriate tool

CapabilityExcelGoogle Sheets
Formula cleaningTRIM, CLEAN, SUBSTITUTE, VALUE; NUMBERVALUETRIM, CLEAN, SUBSTITUTE, VALUE; REGEXREPLACE
DuplicatesConditional formatting, Remove Duplicates, Power QueryConditional formatting, Remove duplicates, UNIQUE
Date and localeRegional parsing, Power Query Change Type Using LocaleFile locale and formula-based construction
Repeatable importPower Query applied steps and refresh where supportedFormula layers and repeatable scripted/connected workflows
CollaborationWorkbook sharing and coauthoring depending on platformBrowser-based shared spreadsheet
Very large dataDesktop features can be useful; size and memory still matterPerformance affected by broad array formulas and sheet complexity
Audit trailSeparate raw, applied steps, issue and validation tabsSeparate raw, formula, issue and validation tabs

Excel is especially useful when a supported desktop Power Query workflow needs to be refreshed repeatedly from CSV files. Google Sheets is attractive for collaborative exercises, formulas and browser-based review. Neither product can automatically decide whether a strange value reflects a genuine event, and neither replaces source documentation. For comparisons with earlier lessons, see Excel for Data Analysis, Google Sheets for Data Analysis and Create an Excel Dashboard.

Complete ten-stage capstone: from raw CSV to an audited result

Complete the following tasks twice: first using Excel and then using Google Sheets. Use the same 250 source rows in both environments, preserve every raw observation, document differences in functions or locale, and independently reconcile your output to the answer workbook. The goal is not to make all rows look similar. The goal is to explain and defend why each accepted record can be analysed and each unresolved record is held separately.

Capstone 1: Profile the source

Method: Count 250 observations, 12 columns and list the planned issue categories. Use filters, COUNTA and COUNTBLANK. Verified outcome or check: Do not confuse a blank SessionID with a missing source row. Common mistake and challenge: What changes if you use the ID column as the denominator?

Capstone 2: Investigate duplicate identifiers

Method: Use COUNTIF to flag candidate repeated keys. Compare complete rows and distinguish exact copies from conflicts. Verified outcome or check: Expect two later exact copies plus the S0097 collision. Common mistake and challenge: Which learner-resource repeats are legitimate?

Capstone 3: Normalize whitespace

Method: Use TRIM for ordinary spaces; explicitly replace U+00A0; inspect control characters. Verified outcome or check: Check that Biology and Computer Science normalize as intended. Common mistake and challenge: Which invisible symbols remain outside these formulas?

Capstone 4: Map subject categories

Method: Maintain a controlled mapping table; correct Bio, Biolgy and Chem while flagging unknown categories. Verified outcome or check: Astronomee remains unresolved, not guessed. Common mistake and challenge: How would you request source approval for a new category?

Capstone 5: Apply field-specific missingness

Method: Keep blank optional rating and duration fields missing; quarantine missing required identifiers or categories. Verified outcome or check: Do not replace missing duration with zero. Common mistake and challenge: How can missingness influence a survey analysis?

Capstone 6: Convert validated numeric text

Method: Separate numeric measures from identifier codes; test VALUE or NUMBERVALUE with known locale. Verified outcome or check: The source 3,5 means 3.5 under its documented source convention. Common mistake and challenge: Would 1,250 represent the same amount everywhere?

Capstone 7: Resolve valid dates safely

Method: Convert documented ISO/text-month dates; quarantine ambiguous and impossible dates. Verified outcome or check: 04/05/2025 and 2025-02-30 remain unresolved. Common mistake and challenge: What evidence would justify a corrected date?

Capstone 8: Screen numerical anomalies

Method: Flag negative durations, large values and ratings outside 1–5; document review policy. Verified outcome or check: Never label an outlier wrong solely from a box plot. Common mistake and challenge: What is the mean’s sensitivity to one extreme value?

Capstone 9: Validate the accepted table

Method: Check uniqueness, keys, categories, numeric types, optional blanks and date validity. Verified outcome or check: No unresolved blocker remains inside the 234 accepted rows. Common mistake and challenge: Can you independently prove IDs remain unique?

Capstone 10: Prepare the signed quality report

Method: Report raw, accepted, corrected and quarantined counts with a change log and limitations. Verified outcome or check: 250 = 234 + 16, and 234 = 19 corrected + 215 unchanged. Common mistake and challenge: What could still be inaccurate even after these checks?

Twenty student exercises with hints and collapsible solutions

Attempt the exercises without immediately opening the answers. Each exercise has a distinct learning objective. Click the solution when you have an independent result; explain why that result is justified. Where a decision depends on missing source evidence, the correct analytical response may be to retain a flagged observation rather than invent an answer.

Exercise 1 (Level 1): Find missing required fields

Objective: Locate blank SessionID and Subject entries. Hint: Compare columns against Data_Dictionary requiredness.

Show solution and explanation

Source rows 49 and 50 contain missing SessionID and Subject respectively.

Common mistake: Do not treat every optional blank as a violation.

Exercise 2 (Level 1): Find leading and trailing spaces

Objective: Inspect the Subject column for boundary whitespace. Hint: Compare TRIM before/after.

Show solution and explanation

Source row 5 contains ‘ Biology ‘ and normalizes to Biology.

Common mistake: Visual similarity does not prove exact text equality.

Exercise 3 (Level 1): Detect numeric values stored as text

Objective: Find one text duration. Hint: Use ISNUMBER; do not rely on right alignment alone.

Show solution and explanation

Source row 24 contains the numeric-looking text ’45’.

Common mistake: Never assume a numeric-looking ID is a measure.

Exercise 4 (Level 1): Classify duplicate SessionIDs

Objective: Locate a conflicting ID and describe why it differs from an exact copy. Hint: Compare all 12 fields.

Show solution and explanation

S0097 occurs on source rows 98 and 99 with different values; both need review.

Common mistake: Deleting one arbitrarily hides unresolved facts.

Exercise 5 (Level 1): Find inconsistent subjects

Objective: List approved and unapproved Subject labels. Hint: Use the controlled category list.

Show solution and explanation

Bio, Biolgy and Chem have documented replacements.

Common mistake: Unknown Astronomee is not automatically mapped.

Exercise 6 (Level 2): Use TRIM

Objective: Clean a value with ordinary spaces. Hint: Test =TRIM(A2) in a copied cell.

Show solution and explanation

‘ Biology ‘ becomes ‘Biology’.

Common mistake: TRIM does not remove every Unicode whitespace character.

Exercise 7 (Level 2): Use CLEAN

Objective: Investigate an ASCII control character. Hint: Test CLEAN on a source example.

Show solution and explanation

CLEAN removes the targeted vertical-tab control character in a text sample.

Common mistake: Check that a removed character was not a necessary separator.

Exercise 8 (Level 2): Combine SUBSTITUTE and TRIM

Objective: Remove U+00A0 from a trailing position. Hint: Use CHAR(160).

Show solution and explanation

=TRIM(SUBSTITUTE(A2,CHAR(160),” “)) produces Biology.

Common mistake: The formula is not a universal Unicode cleaner.

Exercise 9 (Level 2): Convert decimal-comma text

Objective: Interpret a numeric string using documented locale. Hint: Do not guess separator conventions.

Show solution and explanation

The documented fictional ‘3,5’ means 3.5.

Common mistake: Without source locale, a comma may be grouping punctuation.

Exercise 10 (Level 2): Standardize an alias

Objective: Map the misspelled Subject Biolgy. Hint: Use an explicit approved mapping.

Show solution and explanation

Biolgy maps to Biology in this project’s dictionary.

Common mistake: Avoid generic approximate matching without review.

Exercise 11 (Level 3): Interpret ambiguous dates

Objective: Decide what to do with 04/05/2025. Hint: List the two possible conventions.

Show solution and explanation

Keep the source row quarantined pending evidence of day/month order.

Common mistake: Do not choose April 5 merely because your local setting prefers it.

Exercise 12 (Level 3): Resolve exact duplicates

Objective: Determine which copy may be removed. Hint: Compare all columns and preserve original first occurrence.

Show solution and explanation

The later exact copies at source rows 250 and 251 are excluded.

Common mistake: Same learner and resource is not necessarily the same event.

Exercise 13 (Level 3): Assess an outlier

Objective: Investigate a 9000-minute record. Hint: Compare values, units and source system behavior.

Show solution and explanation

Keep it outside accepted analysis pending verification; do not invent a new duration.

Common mistake: An IQR fence detects unusual values, not guaranteed errors.

Exercise 14 (Level 3): Handle missing minutes

Objective: Explain how to compute a valid average. Hint: Separate measured and unmeasured observations.

Show solution and explanation

One accepted duration is missing; mean = 18,982.5 / 233 = 81.47.

Common mistake: Dividing by 234 treats missing as zero.

Exercise 15 (Level 3): Check foreign keys

Objective: Find an unmatched resource. Hint: Use COUNTIF against a 24-key reference list.

Show solution and explanation

R9999 does not match R0001–R0024 and is quarantined.

Common mistake: Never substitute an arbitrary valid ResourceID.

Exercise 16 (Level 4): Explain Power Query applied steps

Objective: Describe a repeatable trimming transformation. Hint: Look for the Applied Steps pane.

Show solution and explanation

A Text.Trim / Text.Clean step can be refreshed; still needs exception review.

Common mistake: A static XLSX tab does not prove a query is embedded.

Exercise 17 (Level 4): Try a Sheets regex function

Objective: Collapse repeated ordinary spaces. Hint: Use the RE2-supported expression ‘ {2,}’.

Show solution and explanation

=REGEXREPLACE(A2,” {2,}”,” “) collapses repeated ASCII spaces.

Common mistake: It does not handle every Unicode class.

Exercise 18 (Level 4): Reconcile record counts

Objective: Prove the output has no unreported losses. Hint: Add accepted and quarantined rows.

Show solution and explanation

250 = 234 + 16; exactly 234 rows are accepted.

Common mistake: Do not sum overlapping issue types as distinct rows.

Exercise 19 (Level 4): Check ID uniqueness

Objective: Check all accepted SessionIDs are distinct. Hint: Compare unique-ID count with row count.

Show solution and explanation

234 accepted records have 234 distinct SessionIDs.

Common mistake: A missing SessionID must not be treated as unique.

Exercise 20 (Level 4): Write an auditable change log

Objective: Document the S0097 decision. Hint: Include source rows, issue, method, evidence and reviewer.

Show solution and explanation

Record both conflicting rows as pending review until source evidence arrives.

Common mistake: Do not present a quarantined record as corrected.

Four-week learning roadmap

WeekFocusSuggested practice and outcome
1: Data quality fundamentalsStudy data types, uniqueness, missingness and category standardsProfile the raw project, write the dictionary and explain why strange is not always wrong
2: Excel cleaningPractice TRIM, CLEAN, SUBSTITUTE, lookups and Power QueryBuild a reproducible cleaning copy and inspect applied transformations
3: Google Sheets cleaningPractice bounded formulas, REGEXREPLACE, dropdowns and source protectionsReproduce the first program’s decisions with transparent formula columns
4: Capstone and auditReconcile 250 source rows, validate accepted IDs and write the reportDefend each quarantine decision and submit a complete change log

This is a flexible beginner timetable rather than a guarantee of mastery. A student may spend more time on the date-and-locale exercises than on simple text cleanup. The important evidence of learning is the ability to justify a decision, reproduce a transformation and independently check the outcome—not speed.

Twenty common data-cleaning mistakes to avoid

Before submitting the project, audit the following avoidable mistakes. For each one, ask whether it could create a false category, erase a valid observation, damage provenance or conceal uncertainty. The safest correction is usually to preserve source evidence, apply a documented field-level rule and rerun the quality report.

  1. Editing or deleting the only raw export — correction: document the source, investigate and verify before making a destructive change.
  2. Removing every repeated learner-resource pair — correction: document the source, investigate and verify before making a destructive change.
  3. Confusing missing durations with genuine zero-minute sessions — correction: document the source, investigate and verify before making a destructive change.
  4. Assuming TRIM removes every invisible character — correction: document the source, investigate and verify before making a destructive change.
  5. Applying PROPER to all identifiers and brand labels — correction: document the source, investigate and verify before making a destructive change.
  6. Converting five-character learner codes to numbers — correction: document the source, investigate and verify before making a destructive change.
  7. Guessing day/month order for slash dates — correction: document the source, investigate and verify before making a destructive change.
  8. Formatting a text date without parsing it — correction: document the source, investigate and verify before making a destructive change.
  9. Ignoring decimal and thousands-separator conventions — correction: document the source, investigate and verify before making a destructive change.
  10. Filling all missing values with the mean — correction: document the source, investigate and verify before making a destructive change.
  11. Deleting all statistical outliers — correction: document the source, investigate and verify before making a destructive change.
  12. Guessing unknown categories from approximate spelling — correction: document the source, investigate and verify before making a destructive change.
  13. Using IFERROR to hide important conversion failures — correction: document the source, investigate and verify before making a destructive change.
  14. Ignoring broken ResourceID lookups — correction: document the source, investigate and verify before making a destructive change.
  15. Using a single validation rule for unrelated columns — correction: document the source, investigate and verify before making a destructive change.
  16. Failing to record which rows changed — correction: document the source, investigate and verify before making a destructive change.
  17. Comparing statistics calculated on different populations — correction: document the source, investigate and verify before making a destructive change.
  18. Trusting automated cleanup suggestions without review — correction: document the source, investigate and verify before making a destructive change.
  19. Celebrating lower error counts while hiding lost observations — correction: document the source, investigate and verify before making a destructive change.
  20. Calling a dataset clean without independent validation — correction: document the source, investigate and verify before making a destructive change.

Ethics, privacy, and accountable data-handling

The fictional workbook deliberately avoids names, emails, phone numbers, personal grades and real student records. In real projects, students must collect only information necessary for the question, use data with appropriate authorization, respect sharing permissions and disclose limitations. Removing obvious identifiers does not automatically anonymize records: combinations of dates, locations and rare categories may permit re-identification. Use appropriate access controls and avoid public links to restricted raw files.

Every substantive change should have a ChangeID, date, affected field, original issue, cleaning rule, number of affected rows, evidence, validation outcome and reviewer. Keep unresolved ambiguities in a separate register. These practices make projects easier to review, correct and update if new source evidence becomes available. They also make automated reports safer, because refreshes can be evaluated against the same explicit rules.

Downloadable companion project resources

The teaching package contains the original 250-row CSV, a separate 234-row accepted CSV, Excel starter and complete workbooks, an issue register, a change log, the 20 exercises and answers, a formula guide, data-quality checklist, audit-report template and a sample Power Query M file. Availability note: the companion files were generated and checked for this article, but their WordPress media-library URLs are not yet verified; therefore this section does not publish fictitious or broken download links. The complete package can be supplied directly as a downloadable file with the lesson.

Optional learning resources: Coursera and Udemy

For deeper practice, explore introductory spreadsheet and data-preparation training. These suggestions are optional and are not prerequisites for the complete free exercise. Course availability, prices, assessments and credentials should be checked with the provider; approved affiliate tracking was not available for verification, so the links below are ordinary informational links rather than represented as tracked affiliate offers.

Coursera: Google Sheets learning

Extend your understanding of data cleaning, spreadsheet formulas and reliable data handling.

Explore the course information

Udemy: Spreadsheet practice

Compare course outlines and practise editing structured data in your own workbook.

Explore the course information

Frequently asked questions

What is data cleaning?

It is the documented investigation and appropriate correction, preservation, exclusion or flagging of data-quality problems for a defined analytical purpose.

How do I clean messy data in Excel?

Preserve the source, profile each column, use supported functions and Power Query steps, inspect duplicates and ambiguous values, then reconcile totals and record changes.

How can I clean data in Google Sheets?

Import a protected copy, use Data cleanup, formulas including TRIM and REGEXREPLACE, validation rules, review flags and a separate Clean_Final tab.

What is the difference between TRIM and CLEAN?

TRIM addresses ordinary spaces around and between words; CLEAN removes a supported set of nonprinting characters. Neither is a universal Unicode cleaner.

Should I remove duplicate rows?

Only when the observation key and full record comparison establish they are unintended copies. Legitimate repeated activity must be retained.

What if a cell is blank?

First determine whether the field is required, optional, not applicable or unknown. Never assume a blank equals numerical zero.

How do I turn text into a number?

Verify whether the field is a measure, confirm decimal and grouping conventions, then use a compatible conversion such as VALUE or Excel NUMBERVALUE.

How should I fix an ambiguous date?

Use source metadata or authoritative clarification to establish day/month order. Without it, flag the value for review rather than guessing.

Can Power Query automate data cleaning?

It can repeat documented transformation steps when supported in Excel, but it does not automatically resolve every ambiguous record or guarantee analytical validity.

How do I know the dataset is clean?

Validate requiredness, types, keys, allowed categories, accepted row counts, missingness and summary calculations independently; report unresolved limitations.

Are outliers necessarily wrong?

No. Statistical outlier flags identify unusual observations for investigation; retention depends on evidence, purpose and documented policy.

Is Google Sheets better than Excel?

Google Sheets emphasizes browser collaboration and regex tools; supported desktop Excel includes powerful Power Query workflows. Choose based on requirements and platform.

Conclusion: clean for truth, not merely neatness

Successful data cleaning is not measured by how many suspicious rows disappear. It is measured by whether the remaining information is more trustworthy, internally consistent, traceable to the source and suitable for a declared analytical purpose. The full sequence is Inspect → Preserve → Profile → Detect → Investigate → Clean → Validate → Document → Analyse. Every stage protects readers against a different kind of misleading result.

Our fictional project demonstrates the point with measurable outcomes: 250 source observations remain documented; 234 accepted records satisfy the defined practice requirements; 16 unresolved or exact-copy records are separated with reasons; 19 accepted rows receive defensible normalizations; and 215 accepted rows remain unchanged. The accepted total of 18,982.5 measured minutes and 156 completed sessions can be explained and recomputed, not merely displayed on a graph.

Use the starter workbook first, then compare your decisions with the complete version and answer guide. Reproduce the audit separately in Excel and Google Sheets, note where versions and locales alter formulas, and resist the temptation to change unknown facts into convenient ones. When you are ready to work with relational data, continue to the next lesson, SQL Joins Explained: INNER JOIN, LEFT JOIN and RIGHT JOIN with Examples.

Interim featured photograph: Christin Hume / Unsplash. An original generated Topic 71 image is included in the companion resource package but has not been substituted for this published image.

Official documentation and further reading

Related Notes for SHS lessons