Data Quality Explained: Missing Values, Outliers and Common Errors
A student receives a ten-row assessment spreadsheet that appears ready for analysis. But one student has no recorded mark, another has the text “N/A”, a score is 105 even though the maximum is 100, two rows describe the same assessment, and a date contains month 13. A different student genuinely scored zero. If the student clicks “Remove Duplicates” and “Replace Blanks with Average” without investigating, the spreadsheet may look neater while becoming less trustworthy. Which observations are errors, which are uncertain, and how can a researcher demonstrate that a cleaning decision was justified?
Data quality is the foundation of reliable descriptive statistics, dashboards, machine learning and scientific research. This practical guide explains the six core dimensions of data quality, different missing-value representations, missingness mechanisms, duplicates, invalid values, dates, inconsistent categories, outliers and responsible cleaning decisions. You will audit a fully reproducible synthetic assessment system, use Excel and Google Sheets-compatible formulas, execute Python and Pandas checks, compare quality measures before and after treatment, and complete 30 original practice questions with hidden worked answers.
The central workflow is Inspect → Profile → Identify → Classify → Investigate → Decide → Clean or Quarantine → Validate → Compare → Document. The distinction between detecting and correcting an issue matters at every stage: a value may be unlikely without being incorrect; a blank may remain unresolved despite careful investigation; and two rows with matching students may be legitimate repeat events when the database’s business rules permit them. All project records in this article are fictional; nothing here reports real student performance.
Verified project snapshot: 240 pristine fictional assessment records; 252 deliberately corrupted imported rows including 12 appended business-key duplicates. The raw file has 18 missing scores, eight out-of-range scores, ten nonstandard levels and seven invalid/ambiguous dates. The analysis-ready file has 240 unique rows and 12 explicitly unresolved missing scores. It is not represented as perfectly repaired.
What is data quality, in simple terms?
Data quality describes how well data satisfy requirements for a particular purpose. A student grade dataset used to calculate a class average needs valid score ranges, trustworthy student identifiers and adequately observed results. A dataset used only to count enrolled learners may still answer that question even if an optional preference column is blank. Consequently, data quality is contextual: a file can be suitable for one legitimate task and unsuitable for another. The absence of obvious errors is not proof of accuracy, and every file need not be perfect in every dimension before it has any analytical value.
Reliable data help analysts avoid biased summaries, misleading charts, failed joins, incorrect model training and poor decisions. Unreliable data can create false high scores, double-count customers or students, invalidate time comparisons and contaminate model evaluation. In the previous Data Visualization guide, we distinguished 720 interactions from 240 student profiles; the same principle applies here: learn what each record represents before computing any metric. The older Excel and Google Sheets data-cleaning tutorial remains a useful companion for interface-based practice.
Six fundamental dimensions of data quality
The UK Government Data Quality Framework describes six widely useful dimensions: completeness, uniqueness, consistency, timeliness, validity and accuracy. They are distinct checks rather than six interchangeable synonyms. Their importance depends on the dataset’s function and the decision it supports. Most practical quality reports should show the dimensions separately rather than invent a universal all-green percentage that conceals unresolved problems.

| Dimension | What it means | Illustrative question | Recommended check |
|---|---|---|---|
| Completeness | Required values and records are present | Are students’ needed scores observed? | Count blank and documented missing markers |
| Uniqueness | No unintended repeated logical observations | Was one assessment imported twice? | Check StudentCode + AssessmentID |
| Consistency | Linked records and representations agree | Do two sources contradict a study level? | Cross-field and cross-table comparison |
| Timeliness | Data arrive or are updated when needed | Is attendance available before reporting? | Timestamp and deadline policy |
| Validity | Values conform to rules and formats | Is 105 allowed out of 100? | Type, range, code list, date parsing |
| Accuracy | Values match the underlying facts | Was 78 entered when the source says 87? | Verify against trusted evidence |
Validity is not accuracy. The recorded value 78 passes a 0–100 rule, so it is valid, but it is inaccurate if a reliable original result shows 87. Likewise, a dataset can be 100% complete and full of wrong information. Accuracy is difficult to score when trustworthy reference evidence is unavailable; a validation script should never label every passing value “accurate” merely because it has the correct type or range. This difference is one reason correction logs need an evidence field.
Start with the ten-row teaching dataset
The small example defines one assessment event per fictional StudentCode with valid score range 0–100 and date format YYYY-MM-DD. It includes 10 imported rows but only nine distinct student codes. The repeated ST05 row is an excess business observation for this stated teaching setup. R03 is blank, R07 says N/A, R04 records score 105, R08 contains impossible date 2026-13-01, and R10 records a valid zero. These are deliberately different situations requiring different decisions.

The score-missing percentage is 2/10×100=20%; raw-row score completeness is 8/10×100=80%. After checking the duplicate, the underlying business-record denominator is nine, not ten. A changed percentage following deduplication is not by itself evidence that quality improved or deteriorated; it may simply reflect a different unit of analysis. In this exercise the zero is valid and must remain zero. The impossible score should be verified against the original assessment rather than automatically changed to 100.
Missing data: blanks, sentinels and legitimate zeros
A missing value is an unavailable recorded value, not always an empty-looking cell. Common representations include blank cells, database NULL, Pandas NaN or pd.NA, missing dates (NaT) and documented strings such as N/A, Unknown or −999. The meaning is field-specific: “NA” could also be a legitimate geographical or category code, and −999 might represent a real measurement in another context. Read the data dictionary before globally replacing sentinel text. In the mini example, the score-column conventions specify that both blank and N/A mean unavailable scores.

The general calculation is missing percentage = missing eligible entries ÷ eligible entries × 100. A numerator without a denominator is not a quality measure. If scores are required only for a subset of eligible assessments, measure missingness against that subset. In our 252-row imported file, there are 18 missing score entries, or 7.14%; 234/252 score fields are observed, or 92.86% complete. This field-level raw-import statistic is not equivalent to the percentage of distinct students with a score. Both definitions can be useful if they are labelled and not mixed.

MCAR, MAR and MNAR: why values may be missing
Statistical handling of missing values depends partly on why observations are unavailable. Missing Completely at Random (MCAR) means that, under the relevant model, the chance of missingness is independent of the observed and unobserved values. An equipment failure that randomly loses some responses could approximately resemble MCAR, although real loss mechanisms need investigation. MCAR is a strong assumption, not a conclusion obtained just because blank spreadsheet cells seem scattered.
Missing at Random (MAR) means that after conditioning on suitable observed information, missingness no longer depends on the unobserved missing value. For example, if follow-up scores are more often missing in a recorded study-level group but not related to the unobserved score after accounting for study level, MAR might be plausible. Missing Not at Random (MNAR) involves dependence on unobserved outcomes or inadequately captured factors; perhaps students with unrecorded lower scores are less willing to submit their results. Neither MAR nor MNAR can generally be established with certainty by examining blanks alone. Use study knowledge, analyses and sensitivity scenarios rather than labelling every dataset automatically.
Should missing rows be deleted or their values replaced?
Before deletion or imputation, ask whether missingness affects the research question, whether the source record can be recovered, and what assumptions each remedy introduces. Complete-case analysis uses only records containing all variables needed for a particular calculation. It is sometimes transparent and practical, but excluding units can reduce precision or bias results when omissions relate to outcomes. A complete-case subset is not a universal new “clean dataset”; other analyses may still use records whose missing fields are irrelevant.
| Treatment | Possible justification | Limitation |
|---|---|---|
| Keep missing and disclose | Value cannot be verified, field not needed everywhere | Some calculations exclude rows |
| Retrieve from verified source | Trusted underlying result exists | Evidence may be unavailable |
| Delete from one analysis | Explicit inclusion rule and justified missingness assumptions | Possible bias and sample reduction |
| Mean / median imputation | Simple teaching baseline for a numeric feature | Distorts variance and relationships |
| Mode imputation | Clearly defined categorical policy and ties | Can inflate most common category |
| Missingness indicator | Missingness itself may predict outcomes | Does not recover true value |
| Multiple imputation | Model-based treatment of missing-data uncertainty | Requires assumptions, specialized analysis |
Mean imputation substitutes the average of observed numeric values; median imputation substitutes the middle observed value. Both can help make algorithms accept feature matrices but can shrink variation and distort associations. In skewed data, the median is often less sensitive to extremes, yet it is not automatically unbiased. Mode imputation changes category frequencies and needs documented tie handling. Do not impute missing outcome labels merely to create apparently complete machine-learning ground truth. Groupwise estimates, forward/backward filling, regression or K-nearest-neighbour imputation can sometimes be appropriate, but only with justified grouping, time order, prediction availability and validation.
Our synthetic project makes a deliberate distinction: six missing scores can be retrieved from a known authoritative synthetic reference; 12 others remain unresolved in the analysis-ready file to demonstrate what honest uncertainty looks like. A researcher without access to the original source would not be entitled to recover the six merely by guessing their expected values. When training a predictive model, split data first and fit imputation parameters using the training set only, then apply the fitted transformation to the test set. Scikit-learn’s imputation documentation provides more advanced methods and their assumptions.
Duplicates: define the business key before deleting anything
An exact duplicate repeats a substantive record; a business-key duplicate violates a rule governing which real-world observation should be unique; a near duplicate merely resembles another row and may or may not be erroneous. Our clean reference defines one record per fictional student in assessment ASSESS-2026-10-A, so the composite key (StudentCode, AssessmentID) must be unique. It is incorrect to deduplicate every repeated StudentCode in an activity-events table, where one student may legitimately have hundreds of separate sessions.
The raw assessment project deliberately appends 12 repeat observations with new ImportRowID values. Thus it contains 252 imported rows but 240 unique logical assessment keys. When duplicated(...,keep=False) marks every member of a duplicate group, it flags 24 rows in these twelve pairs; when counting excess repeated observations, the answer is 12. Both results are mathematically correct for their respective definitions. Retain the original evidence and quarantine only the known redundant imported copies after checking the record content and source history.

How to investigate a duplicate responsibly
First state the entity and unique key, then find repeats, compare every relevant field, review dates and source systems, and establish a defensible retention policy. Two rows with the same key but different marks are a conflict, not proof that either one is correct. Selecting whichever mark is larger or whichever timestamp is newest may introduce inaccuracies. Choose the authoritative record under known system rules, or quarantine unresolved conflicts. Save which row was retained, which row was excluded and the evidence connecting them to the same underlying observation.
Invalid values, incorrect types and controlled categories
A value is invalid when it violates a documented constraint: score 105 exceeds a maximum of 100, negative weekly study hours violate a nonnegative rule, and attendance above 100% violates a percentage range. But the correct replacement for 105 cannot be inferred from the fact that it is wrong. It might be 95, 10.5, or a transcription from another grading scale. Never cap it to 100 merely to make a validation pass. Investigate a trusted source; until then, preserve the raw value and mark it unresolved or ineligible for specific analyses.
Likewise, nonstandard categories can fragment summaries. “Level A,” “level a,” “LEVEL A” and “Level-A” may be variants of the same intended label, but the mapping must come from an approved vocabulary. Trim ordinary surrounding spaces, normalize only where meaning is unambiguous, and log the old and new label. Parsing a text string such as “ 82 ” as numeric 82 is usually reasonable with a traceable rule; converting StudentCode “ST0007” to a number would destroy its identity. Leading zeros, text identifiers and category labels are data, not formatting clutter.
Dates, time zones and unit consistency
Dates deserve a dedicated rule. Under documented YYYY-MM-DD format, “2026-13-01” has impossible month 13. “03/04/2026” is ambiguous across date-order conventions; a spreadsheet may silently interpret it as March 4 or April 3. CSV imports can also convert IDs to dates or use locale-specific decimal separators. Parse dates with an explicit format, verify calendar validity, and retain unparseable original strings for review. For timestamps spanning regions, document local time and UTC conversion separately rather than treating a date-only field as a universal instant.
Unit inconsistencies can remain hidden because numbers look plausible. A study-hours field containing “120 min” and values expressed as “2 hours” needs explicit conversion to one standard unit; attendance stored as fractions 0.85 and percentages 85 requires a documented scale. A result of 40 out of 50 is not equivalent to 40 out of 100; the percentage formula is obtained score ÷ valid positive maximum score ×100. The project includes four unit-labelled anomalies, converted only because their units are known and the original synthetic reference supports their meaning. Unlabelled numbers should not be guessed.
What is an outlier in statistics?
An outlier is an observation unusually distant from other observations according to a stated statistical or contextual criterion. It can arise from a genuine rare event, a different subgroup, data entry mistakes, wrong measurement units or a malfunction. An outlier flag is not proof of error. For example, 99 out of 100 is a rare but legitimate score under a valid assessment; a score of 105 out of 100 violates an objective range rule. The first may warrant sensitivity analysis, while the second requires investigation of an invalid value. The NIST guidance on detecting outliers distinguishes identification, labelling and robust accommodation rather than treating deletion as automatic.
Worked IQR example: 4, 5, 6, 7, 8, 9, 40
Sort the seven values: 4, 5, 6, 7, 8, 9, 40. For this lesson use the median-of-halves convention excluding the middle observation when the number of data points is odd. The middle value is 7, the lower half is 4, 5, 6 and the upper half is 8, 9, 40. Their medians are Q1=5 and Q3=9. Therefore IQR=9−5=4; the lower fence is 5−1.5×4=−1 and upper fence is 9+1.5×4=15. The value 40 exceeds the upper fence and is flagged for review.
Sorted sample = [4, 5, 6, 7, 8, 9, 40]
Median = 7; lower half = [4, 5, 6]; upper = [8, 9, 40]
Q1 = 5; Q3 = 9; IQR = 4
Lower fence = 5 - 1.5 * 4 = -1
Upper fence = 9 + 1.5 * 4 = 15
40 > 15 → FLAG FOR INVESTIGATION (not automatic deletion)

Different software quartile conventions can give different Q1 and Q3 values. Pandas’ default quantile function uses an interpolation convention that need not match this classroom median-of-halves method. Reproducible work should state which convention was used and avoid comparing fences calculated from inconsistent definitions. Box-plot whiskers also have method-specific conventions; a labelled point beyond a whisker is a statistical signal, not a verdict on the record’s authenticity.
Z-scores and robust alternatives
A z-score expresses distance from a mean in standard-deviation units: z=(x−mean)/SD. A heuristic such as |z| greater than three is sometimes used to flag potentially extreme observations, especially under roughly symmetric distributions. But both the sample mean and SD shift when a very extreme value enters, so a simple z-score may perform poorly with small samples, skewed measurements or heavy tails. A standardized value may be unusual without being impossible. Choose the threshold based on domain context and state whether population or sample SD was used.
Robust summaries include the median and median absolute deviation (MAD). The raw MAD is the median of |xi−median(x)|. One common modified-z convention is 0.6745(xi−median)/raw MAD when raw MAD is positive. Other software reports a normal-consistent scaled MAD, which is numerically different; these formulas must not be silently interchanged. Robust methods reduce the influence of large values on summaries, but still cannot distinguish a genuine rare observation from an entry error without external evidence.
Should a statistical outlier be removed?
Before removing any flagged point, verify the field’s allowed range, recorded units, source, target-population membership and measurement context. If trusted documentation establishes a transcription error, correct it and log the original. If the value is a valid but unusual observation, retain it and consider a comparison using robust statistics or a clearly documented sensitivity analysis. If its accuracy cannot be determined and it threatens a critical decision, quarantine it for review or explicitly exclude it under a prespecified analysis rule. Never edit a record simply because it changes a mean, regression coefficient or p-value in an inconvenient direction.

Other common data errors and relational integrity
Not every issue is a missing cell or score outlier. Practical audits also check wrong column headings, trailing spaces, hidden characters, encoding problems, mixed decimal separators, truncated exports, incorrect Boolean strings, repeated file imports, inaccurate formulas, malformed identifiers and inconsistent time periods. A CSV can parse “0012” as integer 12 and lose a meaningful code. A join can multiply rows when both input tables contain repeated keys. An analyst should validate data structure and relationships before trusting an attractive summary or chart.
A database primary key identifies one intended entity or observation; a foreign key links a related table to it. If an Activity Events record references a StudentCode absent from Student Profiles, it is an orphan reference. Causes may include an incomplete master-data import, mistyped code or timing difference between systems. Automatically deleting every orphan event can conceal a synchronization problem and bias totals. Investigate the source and log whether the parent record can be restored, the child key can be verified or the relation remains unresolved. Likewise, use one-to-many joins deliberately rather than assuming every merge preserves row counts.
Data profiling: understand the raw file before modifying it
Data profiling describes the systematic inspection of structure, types, counts, missingness, distinct values, keys, date ranges, category frequencies and numerical distributions. It answers “What do we actually have?” before “What should we change?” A useful profile includes imported row count, unique logical keys, score type and range, allowed levels, parseable dates, suspicious extremes and sample source rows. Profiling generally does not modify the raw file. The generated project uses an immutable clean synthetic reference, a raw imported file and separate issue register, so learners can compare an audit with its preserved evidence.
| Checked raw quality indicator | Observed result | Specific denominator or meaning |
|---|---|---|
| Imported rows | 252 | 240 originals + 12 appended repeats |
| Unique logical assessments | 240 | Composite business key |
| Excess duplicate records | 12 | 252−240, not all duplicate-group rows |
| Missing score entries | 18 | 18/252 imported score fields |
| Out-of-range scores | 8 | Against 0–MaximumScore |
| Nonstandard study levels | 10 | Not in approved three-category vocabulary |
| Invalid / ambiguous dates | 7 | YYYY-MM-DD policy |
| Numeric formatting flags | 6 | Recorded import-format issue entries |
| Potentially valid extreme scores | 4 | Retained, not deleted |
| Unit inconsistencies | 4 | Documented conversions required |
Measure quality with transparent denominators
A quality metric needs a named numerator, denominator and eligibility rule. Completeness is present required entries divided by eligible required entries. Uniqueness might be one minus excess duplicate records divided by imported observations, but only under the stated business-key definition. Score validity can be the share of nonmissing checked scores satisfying the permitted range; this is not an accuracy rate. Timeliness requires a defined deadline and date field. Cross-table consistency requires explicit relationships. An accuracy percentage needs a reliable source against which individual values are compared. Reporting separate dimensions is often more informative than combining everything into a single arbitrary quality score.

Verified issue register and before–after scorecard
Our deterministic corruption procedure begins with 240 fictional records, injects issues into disjoint source-row groups, and appends twelve known duplicate business observations. A separate audit register records 69 findings, each with its record identifier, field, rule, original value, supporting evidence, proposed treatment and current status. Exactly 41 findings are corrected, 12 appended duplicate rows quarantined, four unusual but valid scores retained and twelve missing scores unresolved. The analysis-ready table has 240 unique records, not 252, and 228 observed numeric score values. It is valid for calculations whose required variables are present, not necessarily every possible analysis.


The raw file contains 18 missing scores, so imported-row completeness is 234/252≈92.86%. The ready file retains 12 unresolved missing scores in 240 distinct records, giving 228/240=95% score completeness. This is not a universal 95% data-quality grade: accuracy, timeliness and other dimensions are different questions, and the denominator changed after quarantining excess duplicates. No unresolved score was guessed merely to produce a perfect-looking chart. A chart comparing the numeric score distributions therefore uses only the available parseable scores in each named version.

The complete ten-stage data-cleaning workflow
A professional audit should be reproducible from an unchanged source snapshot. First preserve the original, then understand the data dictionary and profile all relevant fields. Detect problems with explicit rules; classify missingness, duplicates, invalid values and statistical anomalies separately. Investigate evidence, decide whether to retain, correct, quarantine, exclude from a specific analysis or impute with limitations, and apply those decisions to a new version. Next run validation, compare counts and summary statistics against the original, and document every material action. Re-running the workflow should reproduce the same dataset and issue-register findings from the same source and rules.
The project demonstrates why “cleaning finished” need not mean “every cell filled.” The recorded statuses distinguish verified corrections from unresolved scores and deliberately retained extreme observations. The original remains available, the quarantined duplicates are separately accounted for, and the scorecard never implies that an excluded observation has been proven erroneous. When reporting any statistic, mention which version and eligible records were used. The audit follows the UK Government’s data quality action planning principle of actionable rules and monitored improvement.
Data cleaning in Microsoft Excel
In Excel, import the ten-row mini example into a protected Raw Data sheet, with StudentCode kept as text and AssessmentDate interpreted under a fixed format. Add a separate validation sheet rather than overwriting observations. The formula =COUNTBLANK(D2:D11) counts genuinely empty score cells if scores occupy D2:D11, but it may not count the literal text “N/A”; count those separately with COUNTIF. Duplicate screening using StudentCode alone is valid only under the mini exercise’s one-assessment-per-student assumption. In the larger project the identifying key combines StudentCode and AssessmentID, so a compound-key helper or multi-column validation is required.
Mini example: StudentCode B2:B11, Score D2:D11
=COUNTBLANK(D2:D11)
=COUNTIF(D2:D11,"N/A")
=COUNTIF($B$2:$B$11,B2)>1
=IF(D2="","MISSING",IF(NOT(ISNUMBER(D2)),"CHECK TYPE",IF(OR(D2<0,D2>100),"INVALID","VALID")))
The last formula flags literal N/A as CHECK TYPE;
review documented missing markers separately.
Use TRIM, CLEAN and controlled lookup mappings for category cleanup; these text functions do not solve every Unicode whitespace or ambiguity problem. Use Data Validation to restrict new values, Conditional Formatting to highlight suspicious entries, and Power Query when a repeatable transformation is more appropriate. Excel’s Remove Duplicates command is destructive for the selected range; use it only after defining the correct identifying columns and preserving raw evidence. The supplied practice workbook contains Raw Data, Clean Reference, Mini Example, Analysis Ready, Issue Register, Quality Scorecard and answer sheets. Standard numeric calculations are formula-driven, while judgment-dependent corrections remain documented decisions.
Cleaning the same data in Google Sheets
In Google Sheets, import the raw CSV, inspect how the locale interpreted dates and numbers, preserve student identifiers as text and create separate validation and issue-log tabs. COUNTBLANK and COUNTIF address missing markers; COUNTIF and UNIQUE help inspect repeated identifiers; TRIM and CLEAN aid ordinary text normalization; and REGEXMATCH can flag strings under a carefully designed pattern. None guarantees a correct category mapping or actual date validity on its own. A regular expression matching “YYYY-MM-DD” shape will still match an impossible month such as 13. Use proper date parsing and policy-based review.
The provided Google Sheets-compatible XLSX is designed for importing into the native application, but this task does not claim that the cloud editor executed it. Recheck formulas and locale settings after import. The documented Google Sheets function list is preferable to copying unsupported function names from another application. Keep a source sheet, a working sheet, a validation result and a review log. Do not delete conflicting rows merely because a formula labels them duplicate-looking; a reviewer must still establish that they are logically redundant.
Python and Pandas: a reproducible audit
Python provides traceable data-quality checks while preserving exact row-level evidence. The included notebook imports the exact project files and executed eight code cells successfully. Begin with read_csv(...,keep_default_na=False) when it is important to inspect raw sentinel strings before deciding how they should be interpreted. Make a working copy, convert only the documented score-column missing markers, inspect conversion failures separately, and flag duplicates using the actual composite business key. Pandas duplicated(...,keep=False) identifies all records in repeated-key groups, which differs from counting only the excess appended rows.
import pandas as pd
raw = pd.read_csv("data-quality-messy-student-data.csv",keep_default_na=False)
df = raw.copy()
score_text = df["AssessmentScore"].astype("string").str.strip()
score_text = score_text.replace({"":pd.NA,"N/A":pd.NA})
df["ScoreNumeric"] = pd.to_numeric(score_text,errors="coerce")
duplicate_group = df.duplicated(["StudentCode","AssessmentID"],keep=False)
print(len(df),df["ScoreNumeric"].isna().sum(),duplicate_group.sum())
# 252 imported rows, 18 missing, 24 rows in duplicate groups
A numeric conversion using errors="coerce" converts unparseable text to missing, which can silently increase apparent missingness. Compare original and converted columns before proceeding. Score rules should use each row’s positive MaximumScore rather than assuming every source assessment uses 100; dates should be parsed with format="%Y-%m-%d" and conversion failures compared with the original nonmissing date text. Categories should use an approved lookup mapping. The notebook records verified checks for 252 raw rows, 12 excess duplicated keys, 18 missing scores, eight invalid score ranges, seven invalid dates and ten nonstandard levels.
scores = pd.to_numeric(raw.AssessmentScore,errors="coerce")
maximum = pd.to_numeric(raw.MaximumScore,errors="coerce")
invalid_score = scores.notna() & ((scores<0)|(scores>maximum))
invalid_date = pd.to_datetime(raw.AssessmentDate,
format="%Y-%m-%d",errors="coerce").isna()
wrong_level = ~raw.StudyLevel.isin(["Level A","Level B","Level C"])
print(invalid_score.sum(),invalid_date.sum(),wrong_level.sum())
# 8, 7, 10
Automated validation and quality tests
Automated tests are valuable because they make rules reproducible. Validate expected columns, data types, uniqueness, positive maxima, allowed study levels, parseable dates, numeric ranges and known foreign-key relationships. A deliberately corrupted raw file should fail relevant rules; hiding those failures or disabling tests just to make all outputs green defeats the purpose. Validation should run again on the version intended for each analysis, and reports should distinguish unresolved optional fields from nonnegotiable constraints. For the analysis-ready project, all business keys are unique and every observed score is within 0–100, but 12 score entries remain unavailable.
ready = pd.read_csv("data-quality-analysis-ready.csv",keep_default_na=False)
assert len(ready)==240
assert not ready.duplicated(["StudentCode","AssessmentID"]).any()
num = pd.to_numeric(ready.AssessmentScore,errors="coerce")
assert num.isna().sum()==12
assert num.dropna().between(0,100).all()
assert ready.StudyLevel.isin(["Level A","Level B","Level C"]).all()
# Passing rules are scoped checks; they do not prove all values accurate.
How data leakage makes machine-learning evaluation unreliable
Data leakage occurs when information unavailable at genuine prediction time influences model construction or its evaluation. Suppose you split student records into training and test sets but first fill missing study hours using a median computed from the entire dataset. Test-set feature values have influenced the preprocessing, potentially exaggerating performance. Instead, define the prediction target and time boundary, split appropriately, fit learned preprocessing on training data only, and apply that fitted transformation to held-out records. Scikit-learn’s Common Pitfalls and Pipeline documentation explain the standard pattern.

A Pipeline can help enforce consistent fitted transformations but does not automatically solve leakage from duplicate students across splits, future-dated fields, target-derived features or an inappropriate random split of repeated observations. Fixed domain rules such as “score must be no greater than MaximumScore” do not learn statistics from test observations; fitted imputation, scaling and feature selection do. Decide whether students must be grouped by StudentCode or whether a time-based test set is necessary. If preprocessing assumptions are uncertain, state and test them rather than claiming a software tool has made leakage impossible.
Choose the right tool for the scale and task
| Tool | Useful role | Caution |
|---|---|---|
| Excel / Google Sheets | Small audits, interactive teaching and manual review | Volatile formulas, locale and type coercion |
| Power Query | Repeatable spreadsheet transformations | Every transformation still needs review |
| Python / Pandas | Programmatic profiling and reproducible issue registers | Coercion can conceal invalid inputs |
| SQL / database constraints | Keys, relational checks, controlled rules | Constraints do not prove business truth |
| Great Expectations / Pandera | Structured programmatic validation checks | Test definitions and failures need maintenance |
| Scikit-learn Pipelines | Training-only learned preprocessing | Not a cure for every leakage source |
Ten-task capstone: Audit, Clean and Validate Fictional Student Records
The companion capstone uses the exact 240-row synthetic clean reference, 252-row deliberately corrupted file, 69-entry issue register and 240-row analysis-ready dataset. Every task asks for a stated objective, dataset, procedure, calculation or code, verified numerical result, interpretation, common pitfall and an extension for further investigation. Complete it before revealing the audit references below. In professional work, the pristine synthetic source would not normally be available as an oracle; the student must distinguish what can be verified from what remains unknown.
Capstone 1: Inspect the raw file
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: 252 rows, 240 unique StudentCode–AssessmentID business keys.
Important limitation: Validate columns, types, allowed categories and imported-row provenance.
Capstone 2: Measure missing score completeness
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: 18 missing scores / 252 imports = 7.1429% missing; 92.8571% present.
Important limitation: Blank and N/A are missing for scores; a zero is valid.
Capstone 3: Detect duplicate observations
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: 12 excess business-key duplicates; 24 records in repeated-key groups.
Important limitation: Use the composite key; quarantine only verified appended repeats.
Capstone 4: Validate numeric fields
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: Eight scores fall outside the documented 0–100 maximum.
Important limitation: Do not automatically turn 105 into 100.
Capstone 5: Investigate study levels and dates
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: Ten nonstandard labels and seven invalid/ambiguous dates.
Important limitation: Only source-verified or unambiguous repairs are acceptable.
Capstone 6: Flag and investigate outliers
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: For 4,5,6,7,8,9,40: Q1=5, Q3=9, IQR=4, fences −1 and 15.
Important limitation: Value 40 needs review rather than automatic removal.
Capstone 7: Design treatment rules
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: Restore six missing scores from known synthetic source, retain 12 unresolved.
Important limitation: Do not assume the synthetic oracle exists in real investigations.
Capstone 8: Apply corrections and issue logging
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: 69 logged findings; 41 corrected, 12 duplicate rows quarantined, four extremes retained, 12 unresolved.
Important limitation: Maintain original value, evidence and disposition.
Capstone 9: Recalculate quality indicators
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: Ready 240 unique rows; 12 missing scores; no invalid scores, dates or study levels.
Important limitation: Denominator shifts from 252 imported to 240 unique records.
Capstone 10: Write an auditable report
Show your method, source evidence and a responsible decision before checking the reference.
Show verified reference
Expected result: State scope, reference data, transformations, issue counts, 228 observed ready scores and residual limitations.
Important limitation: A successful audit is not a claim of perfect accuracy.
Find the Error Before Revealing the Answer: 30 practice questions
These exercises progress from definitions (Questions 1–10) through verified calculations (11–20) to practical research decisions (21–30). Several present an actual problematic value for you to diagnose before revealing the answer. Every question contains a separate hint and worked solution. Use the question-only PDF for exam-style practice, then use the answer guide and audit files to verify calculations. A plausible cleaning choice can have more than one defensible treatment when the source cannot establish what actually happened.
Level 1 — Quality foundations (Questions 1–10)
Question 1 — Define data quality
What does it mean for data to be fit for a purpose?
Show hint
Think of the research question.
Show worked answer
Verified answer: Data meet sufficiently well the requirements of their intended use; quality is contextual.
Common mistake: A visually tidy file may still be inaccurate.
Question 2 — Six dimensions
Name the UK Government framework’s six dimensions.
Show hint
They address presence, duplicates, agreement, time, rules and truth.
Show worked answer
Verified answer: Completeness, uniqueness, consistency, timeliness, validity, accuracy.
Common mistake: A single invented quality percentage conceals differences.
Question 3 — Completeness
What does completeness measure for required scores?
Show hint
Compare present with eligible.
Show worked answer
Verified answer: Presence of required scores; mini example has eight of ten raw score fields observed.
Common mistake: Completeness does not mean all observed values are correct.
Question 4 — Accuracy versus validity
Can a valid 78 still be inaccurate?
Show hint
Compare actual source record.
Show worked answer
Verified answer: Yes. It is range-valid but inaccurate if the confirmed original is 87.
Common mistake: Range checks cannot confirm truth.
Question 5 — Missing representation
Identify the missing score in mini R03 and R07.
Show hint
Look for blank and marker.
Show worked answer
Verified answer: R03 is blank; R07 is N/A under documented score-column rules.
Common mistake: NA can mean something else in a different field.
Question 6 — Blank versus zero
Is score 0 in mini R10 missing?
Show hint
Review permitted score range.
Show worked answer
Verified answer: No. Zero is a permitted observed score in the 0–100 range.
Common mistake: Replacing zero as blank changes results.
Question 7 — Duplicate record
Which mini rows repeat a business observation?
Show hint
Check StudentCode and assessment context.
Show worked answer
Verified answer: R05 and R06 repeat ST05’s same assessment; one excess record.
Common mistake: Repeated students may have legitimate different tests in other datasets.
Question 8 — Invalid score
What is wrong with mini R04=105?
Show hint
Check MaximumScore.
Show worked answer
Verified answer: 105 exceeds permitted 100. Flag and verify; do not cap automatically.
Common mistake: An invalid value does not reveal the intended number.
Question 9 — Category inconsistency
What is wrong with mini `level a`?
Show hint
Compare approved labels.
Show worked answer
Verified answer: It is a nonstandard label; map to Level A only when vocabulary confirms equivalence.
Common mistake: Fuzzy similarity is not proof of same category.
Question 10 — Preserve raw evidence
Why should a source CSV remain unchanged?
Show hint
Think reproducibility.
Show worked answer
Verified answer: For rollback, evidence, audit trail and independent reproduction.
Common mistake: Never overwrite the only raw source.
Level 2 — Calculations and checks (Questions 11–20)
Question 11 — Missing percentage
Compute mini missing-score percentage.
Show hint
2 missing / 10 imported.
Show worked answer
Verified answer: 2/10×100=20%, using the declared raw-row denominator.
Common mistake: Do not use nine unique students without relabelling the denominator.
Question 12 — Completeness percentage
Compute mini raw-row score completeness.
Show hint
Eight present of ten.
Show worked answer
Verified answer: 8/10×100=80%.
Common mistake: Zero counts as observed, not missing.
Question 13 — Duplicate-key count
Raw 252 rows, 240 unique keys: how many excess repeats?
Show hint
Subtract logical keys from rows.
Show worked answer
Verified answer: 252−240=12 excess duplicates; 24 rows appear in duplicate groups.
Common mistake: The two duplicate metrics are different.
Question 14 — Invalid calendar date
Why is 2026-13-01 wrong?
Show hint
Month in YYYY-MM-DD.
Show worked answer
Verified answer: Month 13 is invalid; source verification or quarantine is required.
Common mistake: Do not guess the intended date.
Question 15 — Text numeric type
How should ‘ 82 ‘ be handled as a score?
Show hint
Parse carefully.
Show worked answer
Verified answer: Trim and convert to 82 if unambiguous, preserve original and test bounds.
Common mistake: `errors=coerce` can hide parse failures.
Question 16 — Quartiles
For 4,5,6,7,8,9,40, find Q1 and Q3 using median-of-halves.
Show hint
Exclude overall median 7.
Show worked answer
Verified answer: Lower 4,5,6 gives Q1=5; upper 8,9,40 gives Q3=9.
Common mistake: Different software quantile methods can differ.
Question 17 — IQR
Calculate the interquartile range.
Show hint
Q3−Q1.
Show worked answer
Verified answer: 9−5=4.
Common mistake: IQR does not equal full range.
Question 18 — IQR outlier
Calculate fences and flag any values.
Show hint
Q1−1.5IQR, Q3+1.5IQR.
Show worked answer
Verified answer: Fences −1 and 15; 40 lies above 15 and is flagged.
Common mistake: Flagged does not mean erroneous.
Question 19 — Mean vs median imputation
State limitations of both.
Show hint
Think variance and skew.
Show worked answer
Verified answer: Both can reduce variation; median is less affected by extreme values but neither is universally unbiased.
Common mistake: Neither recovers the actual missing score by definition.
Question 20 — Raw score validity
Of 234 nonmissing raw scores, 8 are out of range. Rate?
Show hint
Subtract eight then divide by 234.
Show worked answer
Verified answer: 226/234×100≈96.58% range-valid among present scores.
Common mistake: Validity rate does not mean 96.58% accurate.
Level 3 — Responsible research decisions (Questions 21–30)
Question 21 — Mixed units
How can 120 min and 2 hours be standardized?
Show hint
Known conversion.
Show worked answer
Verified answer: Both represent 2 hours; convert only after confirming units.
Common mistake: Unlabelled 120 cannot safely be assumed minutes.
Question 22 — Suspicious score 99
Should a 99/100 automatically be removed?
Show hint
Range validity versus statistical rarity.
Show worked answer
Verified answer: No. Investigate source and subgroup; retain valid rare observations unless evidence warrants other handling.
Common mistake: High marks are not errors solely due to rarity.
Question 23 — Foreign-key error
Activity references a StudentCode absent from profiles. What now?
Show hint
Check parent table.
Show worked answer
Verified answer: Flag orphan reference, investigate delayed parent imports, bad keys or synchronization.
Common mistake: Blind deletion may hide a wider pipeline problem.
Question 24 — MCAR versus MAR
Explain the fundamental missingness distinction.
Show hint
Observed covariates matter under MAR.
Show worked answer
Verified answer: MCAR: no dependence on observed or missing variables; MAR: dependence may be explained by observed variables.
Common mistake: Random-looking blanks do not establish MCAR.
Question 25 — MNAR example
Scores are missing more often when the missing scores themselves are low. Which mechanism?
Show hint
Unobserved outcome may matter.
Show worked answer
Verified answer: Potential MNAR; assumptions and sensitivity checks are needed.
Common mistake: Cannot prove MNAR by inspecting the empty cells alone.
Question 26 — Flawed Excel formula
Why can a score-range IF formula mishandle N/A?
Show hint
Type validation first.
Show worked answer
Verified answer: Literal N/A is text; check documented missing markers and ISNUMBER before comparing numeric bounds.
Common mistake: Do not classify N/A as valid numeric.
Question 27 — Pandas keep=False
What does duplicated(keys,keep=False) return?
Show hint
Marks every row of a repeated group.
Show worked answer
Verified answer: 24 rows flagged across 12 duplicate-key pairs; 12 are excess repeats.
Common mistake: Flagged rows count differs from excess duplicate count.
Question 28 — Machine learning leakage
What is wrong with a median fitted before a train/test split?
Show hint
Test distribution influences preprocessing.
Show worked answer
Verified answer: The full-data median leaks information; fit learned preprocessing on training data only.
Common mistake: Pipelines cannot prevent time-based or group leakage automatically.
Question 29 — Audit trail
Propose a reproducible cleaning process.
Show hint
Source, rules, evidence, verification.
Show worked answer
Verified answer: Preserve source; profile; detect; investigate; document decision; transform copy; validate; compare and report.
Common mistake: Do not merely hide unresolved records.
Question 30 — Final audit
Summarize raw, ready and issue outcomes.
Show hint
Use exact verified counts.
Show worked answer
Verified answer: Raw 252; ready 240; 12 duplicate keys, 18 missing scores, eight invalid scores, seven bad dates, ten labels; ready 12 missing; 41 corrected, 12 quarantined, four retained valid, 12 unresolved.
Common mistake: Analysis-ready is not proof every value is accurate.
Forty common mistakes that can damage an audit
The following reference table helps learners identify common failure modes without turning every suspicious record into an automatic deletion. Use it when reviewing imported spreadsheets, data collection processes, model pipelines and published dashboards. Each correction is a rule to investigate, not a claim that one action fits every dataset.
| Incorrect practice | Risk | Responsible alternative |
|---|---|---|
| Assuming import equals accuracy | No independent check | Compare with source evidence |
| Confusing completeness and accuracy | Present values may be false | Assess dimensions separately |
| Validity used as a truth test | In-range can be incorrect | Source-verify critical values |
| Treating zero as missing | Changes genuine scores | Use column codebook |
| Treating every NA as null | Code may be legitimate | Field-specific marker policy |
| Deleting all incomplete rows | Can select biased subset | Check mechanism and analytical need |
| Mean filling without purpose | Shrinks variance | Justify and test alternatives |
| Ignoring missingness mechanisms | May bias estimates | Consider MCAR, MAR, MNAR |
| Hiding missing bars | Distorts visualization | Report missingness explicitly |
| Counting duplicate student as unique | Inflates denominators | Composite business key |
| Deleting genuine repeated events | Loses real activity | Model observation context |
| Wrong duplicate key | Incorrectly merges records | Declare intended uniqueness |
| Ignoring conflicting duplicates | May retain wrong score | Investigate authoritative record |
| Guessing replacement values | Creates fictitious certainty | Use verified correction or flag |
| Capping every score 105 to 100 | Masks source error | Quarantine and verify |
| Removing all outliers | Loses real extremes | Investigate before action |
| Outlier and error conflated | Statistical flag is not proof | Distinguish rule from rarity |
| Unstated quartile formula | Software may disagree | Document quartile convention |
| Universal z-threshold | Poor for skew/small n | Use context and robust checks |
| Silent conversion to NaN | Hides parse failure | Compare before/after text |
| Casting codes to numbers | Loses leading zeros | Preserve ID as text |
| Dropping leading zeros | Breaks key relationships | Fix import type |
| Mixing 0.85 and 85% | 100-fold error | Document percentage scale |
| Mixing minutes and hours | Misleading averages | Normalize verified units |
| Ambiguous date parsing | Wrong time order | Specify date format |
| Ignoring time zones | Mislabels day boundaries | Store timezone policy |
| Fuzzy-merging categories | Changes intended meaning | Controlled vocabulary map |
| Many-to-many join surprise | Multiplies rows | Validate join cardinality |
| Deleting all orphan keys | Conceals upstream issues | Review referential causes |
| Cleaning test set before split | Evaluation contamination | Split before learned preprocessing |
| Median fitted on full sample | Test leakage | Fit imputer on training |
| Overwriting only raw CSV | Destroys evidence | Immutable source snapshot |
| No issue log | Cannot reproduce actions | Record rule, value and evidence |
| Quality score with no denominator | Meaningless comparison | State numerator and population |
| Hiding unresolved issues | False cleanliness | Display unresolved and quarantined |
| Engineering desired p-values | Invalid statistical inference | Predeclare exclusion rules |
| Automatic cleaning claimed infallible | Cannot establish truth | Human review and source checking |
| Synthetic data called real | Misleads students | Disclose fictional construction |
| Ignoring failed assertions | Breaks integrity controls | Treat failure as diagnostic |
| Misleading before/after percentages | Population may change | Label stage and denominator |
Final check: Is this dataset ready for analysis?
Use five essential questions in the article, and the full 20-point audit checklist in the downloadable PDF. A “yes” answers only the specified rule; it does not prove universal correctness.
- Source and scope: Are the population, raw file, business keys and data dictionary documented?
- Completeness and validity: Are missing values, duplicates, dates, categories, score ranges and units checked?
- Evidence-based decisions: Are corrections, retained extremes and quarantined records justified in an issue log?
- Analysis safety: Are unresolved gaps disclosed, relationships tested and learned preprocessing kept out of held-out data?
- Reproducibility: Can another student rerun the checks and obtain the same before-and-after indicators?
Four-week learning roadmap
| Week | Concepts and practical work | Evidence of progress |
|---|---|---|
| 1 — Fundamentals | Six dimensions, missingness, completeness, accuracy and validity | Explain 20% missing in the ten-row mini example |
| 2 — Errors and outliers | Duplicate keys, dates, categories, IQR and outlier decisions | Reproduce Q1=5, Q3=9 and 12 raw duplicate keys |
| 3 — Software workflow | Excel, Sheets, Pandas, issue logs and automated checks | Run the eight-cell notebook and validate output files |
| 4 — Capstone and report | Ten-task project, 30 questions, unresolved issues and findings | Submit an audit report with verifiable metrics |
Learning schedules can be adjusted to students’ prior knowledge. Beginners should first understand the difference between a record, business key and field; more experienced learners can investigate leakage and missing-data assumptions sooner. The important outcome is not memorizing a cleaning command but defending the rule, recording what changed and recognizing which conclusions the available data still cannot support.
Download the companion learning resources
These ten files have been uploaded to the connected Notes for SHS staging media library. The complete learning ZIP supplied in the lesson’s completion report additionally contains the clean reference, corrupted raw data, mini teaching data, issue-register CSV, analysis-ready CSV, executable notebook, source generation rules, all original illustrations and verification report. The online Google Sheets editor was not used, so its accompanying workbook is described as import-compatible rather than natively tested.
- Verified Excel practice workbook
- Verified Google Sheets-compatible workbook
- 30 original practice questions
- Complete worked answers
- Six dimensions guide
- Missing-value decision guide
- IQR and z-score outlier guide
- Twenty-point printable audit checklist
- Ten-task assessment capstone
- Editable audit report template (Word)
Optional structured learning on data cleaning
Students who prefer additional instruction can explore data cleaning courses on Coursera and data cleaning courses on Udemy. These are ordinary provider discovery links, not verified affiliate-tracked URLs: no specific approved tracking parameters or ad creative for this page were confirmed. Review current syllabus, prerequisites and price on the provider’s website before enrolling.
Frequently asked questions about data quality
What is data quality?
The degree to which a dataset is fit for a specific purpose under requirements such as completeness, validity and accuracy.
What are the six data quality dimensions?
Completeness, uniqueness, consistency, timeliness, validity and accuracy.
What is the difference between accuracy and validity?
Validity means passing defined rules; accuracy requires matching trustworthy underlying facts.
Are blank cells and zero scores the same?
No. A recorded zero can be legitimate, while blank or documented sentinel strings may mean unavailable.
Should missing rows be deleted?
Not automatically. Investigate cause, research purpose, eligible population and implications of exclusion or imputation.
What are MCAR, MAR and MNAR?
Missingness mechanisms defined by dependence on observed and unobserved values; they generally require assumptions and cannot simply be read from blank patterns.
What is a business-key duplicate?
A repeated logical observation violating its defined identifying-key rule.
What makes an assessment score invalid?
An observed score outside its documented allowable interval or incompatible with required type/scale.
What is the IQR outlier rule?
Flag values beyond Q1−1.5×IQR or Q3+1.5×IQR under a declared quartile method.
Should every outlier be removed?
No. Statistical rarity is not proof of a recording error; investigate and document any exclusions.
How does Pandas detect missing values?
Use appropriately defined missing markers and isna(), checking source text and conversion errors.
What is data leakage?
Information unavailable at genuine prediction time improperly influencing model training, preprocessing or evaluation.
Conclusion: reliable analysis starts before the first chart
Data quality is not the process of making every spreadsheet cell appear filled. It is the disciplined process of deciding whether data are trustworthy and suitable for a clearly defined analytical purpose. Completeness, uniqueness, consistency, timeliness, validity and accuracy describe different dimensions. Missingness can be structural or informative; duplicates depend on the business observation; an impossible date cannot be corrected by guesswork; and an unusual score may represent something genuine. Strong practice protects the raw source, investigates flagged values, applies documented rules and reports unresolved problems without concealment.
Our 240-record fictional audit illustrates that principle: 252 imported observations contained twelve extra duplicates; the corrected analysis-ready file has 240 unique records but still retains twelve unresolved missing scores. That is not failure—it is transparent, defensible handling of information whose original value has not been recovered. Use the downloadable datasets to repeat the calculations, study the IQR example, complete the 30 questions and submit the capstone report. The next student projects on free datasets and real-world analytics will be more reliable when these data-quality habits become routine.
Official documentation and further reading
- UK Government — Data Quality Framework
- UK Government — Data Quality Action Plan
- NIST — Detection of Outliers
- Pandas — Working with Missing Data
- Pandas — to_numeric
- Scikit-learn — Common Pitfalls
- Scikit-learn — Imputation
- Microsoft Excel — Official Support
- Google Sheets — Function Reference
1 response to “Data Quality Explained: Missing Values, Outliers and Common Errors”