🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Data Cleaning and Preparation for Analysis › Lesson 3
TEC-DATA85-05 · Lesson 3 · 11 clock hours · lab

Handling Missing Data

Objective. Students will diagnose the missingness mechanism (MCAR, MAR, or MNAR) for each variable in a dataset and apply the most appropriate imputation strategy, documenting the rationale in code comments.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Why Missing Data Matters

Real-world datasets are almost never complete. Patient records get skipped, sensors drop readings, and survey respondents leave questions blank. If you ignore missing values or handle them carelessly, every downstream analysis—summary statistics, machine learning models, dashboards—can produce results that are wrong or misleading. Before you impute (fill in) anything, you must ask why the data are missing, because the reason determines the correct remedy.

The Three Missingness Mechanisms

Missing Completely at Random (MCAR) means the probability that a value is missing has nothing to do with any variable in your dataset, observed or unobserved. A lab machine randomly jams and drops a reading regardless of the patient's condition—that is MCAR. Because the missing rows are a random subset of all rows, you can often remove them or use simple imputation without introducing bias. Little's MCAR test (available in Python via the `pyampute` or `statsmodels` ecosystem, and in R) provides a formal statistical check: a non-significant p-value suggests MCAR.

Missing at Random (MAR) means the probability of missingness depends on other observed variables, but not on the missing value itself. For example, older patients may skip a pain-scale question, but once you know age, whether the value is missing is unrelated to what the pain score would have been. MAR is the most common assumption in practice. Model-based methods—multiple imputation, regression imputation—work well here because they can use the related observed variables to estimate the missing values.

Missing Not at Random (MNAR) means the probability of missingness depends on the unobserved value itself. A patient with very high blood pressure may skip reporting it precisely because it is high. MNAR is the most dangerous mechanism because no standard imputation method fully corrects for it. You must either collect more data, use domain knowledge, or at minimum flag the missingness and report its potential impact on conclusions.

Diagnosing Missingness in Practice

Start visually. The `missingno` library in Python produces matrix plots and bar charts that reveal which columns have missing values and whether missingness is clustered in the same rows across columns—a pattern that suggests MAR. After the visual check, apply Little's MCAR test. If the test rejects the null hypothesis (p < 0.05), MCAR is unlikely; proceed to examine correlations between missingness indicators and other columns to distinguish MAR from MNAR.

Create a binary indicator column for each variable with missingness (1 = missing, 0 = observed). Correlate those indicators with other observed variables. Strong correlations suggest MAR. When you have theoretical reasons—supported by subject-matter experts—to believe the missing value itself drives missingness, classify the variable as MNAR.

Four Imputation Strategies

Mean, median, or mode substitution replaces each missing value with the column's central tendency. It is fast and simple, but it shrinks variance and distorts correlations. Use mean for roughly symmetric continuous variables under MCAR; use median when the column is skewed; use mode for nominal or ordinal categorical columns. Never use mean/median/mode for MNAR data.

Pandas forward-fill (`ffill`) propagates the last observed value forward in time-ordered data—useful for sensor readings or time-series vitals. It assumes values change slowly and continuously. Only apply it when the data have a meaningful time or sequence order.

scikit-learn `SimpleImputer` provides a pipeline-friendly way to apply mean, median, mode, or a constant fill value. It is especially valuable when you need the same imputation logic applied consistently during both training and inference in a machine learning pipeline.

Binary missingness-indicator flags do not fill the gap—they add a new column that records whether the original value was missing. This is the primary tool for MNAR variables and can also supplement other methods. The flag lets a model learn that missingness itself is informative.

Evaluating Your Imputation

After imputing, compare the before-and-after distribution of each column using histograms and summary statistics. A good imputation preserves the overall shape of the distribution. If the post-imputation histogram looks dramatically different—particularly if variance collapses to a spike—your method is distorting the data. For MAR variables with many missing values, consider multiple imputation (generating several filled datasets and pooling results) rather than single-value substitution.

Documentation and Rationale

Every imputation decision must be documented in your code. Write comments that state: (1) the diagnosed mechanism, (2) the evidence you used to reach that diagnosis, and (3) why the chosen method is appropriate given that mechanism. This documentation is not optional—it is a professional and ethical obligation. Analyses built on undocumented imputation choices cannot be reproduced or audited, which violates data integrity standards expected in healthcare, finance, and regulated industries.

Data Safety and Integrity Reminders

When working with any dataset that contains personal or health-related information—even synthetic data modeled on real records—follow your organization's data governance policies. Never store real patient data on personal devices. Synthetic datasets used for training should be clearly labeled as such and not mixed with production data. Maintain version control on your notebooks so that imputation decisions are traceable. Accuracy in data preparation is a form of professional safety: a poorly imputed dataset fed into a clinical or financial model can cause real harm.

Key terms9

MCAR (Missing Completely at Random)A missingness mechanism where the probability that a value is missing is unrelated to any variable in the dataset, observed or unobserved; missing rows are a truly random subset of all rows.
MAR (Missing at Random)A missingness mechanism where the probability that a value is missing depends on other observed variables but not on the missing value itself; model-based imputation methods perform well under this assumption.
MNAR (Missing Not at Random)A missingness mechanism where the probability that a value is missing depends on the unobserved value itself; standard imputation cannot fully correct for this and the missingness should be flagged.
ImputationThe process of replacing missing values in a dataset with estimated or substituted values based on a chosen strategy, such as the column mean, a model prediction, or a carried-forward observation.
Little's MCAR TestA statistical hypothesis test that evaluates whether data are missing completely at random; a non-significant result (p ≥ 0.05) is consistent with MCAR, while a significant result suggests MAR or MNAR.
missingness indicatorA binary column added to a dataset that records whether the value in a corresponding column was originally missing (1) or observed (0); used as a feature in models when the mechanism is MNAR.
SimpleImputerA scikit-learn transformer that fills missing values using a specified strategy (mean, median, most frequent, or constant) and integrates into scikit-learn Pipelines for consistent preprocessing.
forward-fill (ffill)A pandas method that replaces each missing value with the most recent preceding observed value in a sequence; appropriate for time-ordered or sensor data where values change gradually.
missingness mechanismThe underlying process or reason that determines why certain values are absent from a dataset; correctly identifying the mechanism (MCAR, MAR, or MNAR) is required before selecting an appropriate imputation strategy.

Worked examples4

1. A column 'body_temp_F' has 40 missing values out of 200 rows. Little's MCAR test returns p = 0.42, and a correlation matrix shows no significant relationship between the missingness indicator for 'body_temp_F' and any other column. Which mechanism applies, and what is the mean imputation value if the observed readings are: 98.2, 99.1, 97.8, 98.6, 100.4 (and 195 similar values with a sum of 19,344.5 across all 195 observed rows)?
  1. Step 1 — Diagnose mechanism: p = 0.42 from Little's MCAR test is not significant (p ≥ 0.05), and no correlations with other variables exist. Classify 'body_temp_F' as MCAR.
  2. Step 2 — Choose strategy: MCAR permits mean substitution without introducing systematic bias. Mean imputation is appropriate.
  3. Step 3 — Calculate mean: Total observed sum = 19,344.5 across 195 observed rows. Mean = 19,344.5 ÷ 195 = 99.2°F (rounded to one decimal place).
  4. Step 4 — Apply: Replace all 40 missing values in 'body_temp_F' with 99.2°F and document in code comments that MCAR was the diagnosed mechanism confirmed by Little's test (p = 0.42).
Answer: Mechanism is MCAR; impute missing values with the column mean of 99.2°F.
2. A column 'pain_score' (0–10 scale) has 60 missing values. The missingness indicator for 'pain_score' correlates strongly with the column 'age' (r = 0.61, p < 0.001), meaning older patients are more likely to leave pain score blank, but the value of the pain score itself does not predict whether it is missing. What mechanism applies, and which imputation approach is most defensible?
  1. Step 1 — Diagnose mechanism: The probability of missingness depends on 'age' (an observed variable), not on the pain score itself. This satisfies the definition of MAR.
  2. Step 2 — Evaluate simple imputation: Mean or median substitution ignores the relationship with age and will introduce bias for older patients whose pain scores differ systematically.
  3. Step 3 — Choose strategy: A model-based approach that uses 'age' (and other observed predictors) to estimate 'pain_score' is most defensible under MAR. In practice, regression imputation or multiple imputation using the observed predictors is preferred.
  4. Step 4 — Minimum acceptable alternative: If regression imputation is not available in the current workflow, use median substitution within age subgroups rather than a single global median, and document the MAR diagnosis and the stratification approach in code comments.
Answer: Mechanism is MAR; regression imputation (or stratified median imputation) using 'age' as a predictor is the most defensible strategy.
3. A column 'blood_pressure_systolic' has 80 missing values. Subject-matter experts confirm that patients with very high blood pressure frequently decline to report it. Little's MCAR test returns p = 0.003. The missingness indicator correlates modestly with age (r = 0.22) but domain knowledge strongly suggests the missing value itself drives non-response. What is the recommended handling approach?
  1. Step 1 — Diagnose mechanism: p = 0.003 rejects MCAR. Domain knowledge indicates patients with high values are more likely to omit the reading, meaning the missing value drives missingness. Classify as MNAR.
  2. Step 2 — Recognize imputation limits: No standard single-imputation method corrects for MNAR bias. Imputing with mean or median will systematically underestimate high blood pressure in the dataset.
  3. Step 3 — Apply missingness indicator: Add a binary column 'bp_systolic_missing' (1 = missing, 0 = observed) so downstream models can treat missingness as a feature carrying predictive information.
  4. Step 4 — Document and report: Note in comments that 'blood_pressure_systolic' is MNAR based on domain knowledge and the significant MCAR test result (p = 0.003). Flag the limitation in any analysis report; recommend data-collection improvements to reduce non-response.
Answer: Mechanism is MNAR; add a binary missingness-indicator flag, avoid relying on mean/median imputation alone, and document the limitation explicitly.
4. A time-series column 'heart_rate_bpm' recorded every minute has scattered missing readings at minutes 5, 6, and 7 out of a 60-minute monitoring window. The observed values around the gap are: minute 4 = 72 bpm, minute 8 = 74 bpm. A colleague proposes forward-fill. Is forward-fill appropriate, and what values would it assign to minutes 5, 6, and 7?
  1. Step 1 — Check applicability: The data are time-ordered and the variable (heart rate) changes gradually. Forward-fill is designed for exactly this scenario.
  2. Step 2 — Diagnose mechanism quickly: The gap (minutes 5–7) appears random and brief with no structural reason tied to the patient's condition. MCAR or MAR is plausible; forward-fill is a reasonable choice for short time-series gaps under either assumption.
  3. Step 3 — Apply forward-fill logic: The last observed value before the gap is minute 4 = 72 bpm. Forward-fill propagates that value forward until the next observed reading. Minutes 5, 6, and 7 each receive 72 bpm.
  4. Step 4 — Evaluate result: The imputed values (72, 72, 72) are close to the post-gap value of 74 bpm, indicating the fill is reasonable. Note in comments that forward-fill was applied to a short gap in time-ordered heart-rate data.
Answer: Forward-fill is appropriate for this time-ordered gap; minutes 5, 6, and 7 are each imputed with 72 bpm (the value at minute 4).

The math in this lesson1

Learners compute a column mean for imputation of MCAR missing values.
S-ID.2
Brush up in the math halls at newSchoolWorks.com:
In class: Instructor-led demonstration (45 min): using a synthetic patient-records dataset, the instructor uses missingno visualizations and Little's MCAR test (via Python) to classify three variables as MCAR, MAR, and MNAR; students follow along and reproduce results in their own notebooks. · Students independently apply four imputation methods—mean/median/mode substitution, pandas forward-fill, sklearn SimpleImputer, and binary missingness-indicator flags—to four assigned columns, then compare post-imputation distributions with before/after histograms and document which method preserves the original distribution best. · Guided reflection: students write a half-page justification for each imputation choice; instructor reviews and returns written feedback within one class session.
Materials: Synthetic patient-records CSV, Jupyter Lab, missingno library, scikit-learn, matplotlib, seaborn, instructor-prepared demonstration notebook
Check: Instructor reviews each notebook; pass requires correct mechanism classification for at least 3 of 4 variables and correctly applied code for all four imputation methods (no runtime errors, before/after plots present) — 75 % rubric score.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data Analysis and Statistics
1. A dataset column fails Little's MCAR test (p = 0.01) and its missingness indicator shows no significant correlation with any other observed column. However, a clinical expert says patients with abnormal results are known to avoid reporting that value. Which mechanism best describes this variable?
Data Cleaning and Preparation
2. Which Python library provides matrix and bar-chart visualizations specifically designed to reveal missingness patterns across columns and rows?
Data Cleaning and Preparation
3. A data analyst applies mean imputation to a column with 35% missing values under a MAR mechanism. Which of the following is the most likely consequence?
Data Cleaning and Preparation
4. Which scikit-learn class allows you to specify an imputation strategy (such as 'median') and integrate that imputation step directly into a machine learning Pipeline?
Data Cleaning and Preparation
5. A time-series column recording hourly temperature sensor readings has a three-hour gap. The analyst applies pandas `ffill()`. What value is assigned to each of the three missing hours?
Data Cleaning and Preparation
6. A binary missingness-indicator flag column is most critically important when a variable is classified as:
Data Analysis and Statistics
7. After applying median imputation to a right-skewed column, an analyst compares before-and-after histograms. Which post-imputation pattern most strongly suggests the imputation was acceptable for a MCAR variable with low missingness (under 5%)?
Data Cleaning and Preparation
8. A student's notebook classifies all four assigned variables as MCAR without running Little's MCAR test or examining missingness correlations, and then applies mean imputation to all four. According to the lesson's pass criteria, which requirement does this notebook most directly fail?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.