Business Analytics & Data Science

B02 · Introductory

Data Cleaning and Preparation

12 lessons

B02 · Module 3, lesson 1 · Lesson 6 of 12

Missing values

A blank cell is a question: why is the value missing? Learn to find every form missing data takes, judge whether the gaps are random, and choose between deleting and imputing without quietly biasing the answer.

About 75 minutes

Before you start

You will be able to

  • Recognise the forms missing data takes in an export, including placeholders such as 0, −999 and “unknown”, and blanks that really mean zero.
  • Distinguish data missing completely at random, at random and not at random, and explain why the data alone cannot settle which applies.
  • Calculate how deletion, mean imputation and group-wise imputation change a mean, a standard deviation and a correlation.
  • Choose between deletion, single imputation, a missing-value indicator and multiple imputation for a stated purpose, and justify the choice.
  • Apply imputation without leakage by computing fill values from training data only.

Review first

  • Profiling a dataset and writing validation rules — Profiling tells you how many values are blank in each column and validation rules catch values that can’t be right; this lesson starts from what they reveal.
  • Calculating a mean and a sample standard deviation (dividing by n − 1).

Fictional case A fictional coffee business founded by Ana Lim. It starts as a catering and barista-training service, opens its own cafés and an online shop for beans, and plans a canned cold brew.

The idea

Fictional case

Lantern Coffee Co. now sells beans and subscriptions through an online shop, and after each delivery customers are invited to rate their order from 1 to 5 stars. Ana Lim wants to put the average rating on the shop’s home page, so she opens a month’s order export and averages the rating column: 4.38 stars. The spreadsheet does not mention that 90 of the 200 rating cells are blank, or that the blanks are not spread evenly. Subscribers rate most of their deliveries; one-off buyers rarely bother.

A missing value is a cell where a value should exist but was not recorded. Every real dataset has them: a customer skips a survey question, a form field is optional, a system crashes mid-export, two files are joined and some rows find no partner. Handling them well takes three steps: find them all, work out why they are missing, then decide what to do. The second step decides whether the third gives an honest answer.

Finding missing values

Missing values rarely label themselves clearly. In the same export you may find several kinds side by side:

  • Empty cells and system markers: a blank, or text such as NA, N/A, NULL or NaN that a database or program wrote in place of a value.
  • Placeholder codes: numbers typed into a field that would not accept a blank, such as 0, −1, −999 or 9999. Harborview Hotel’s booking export, for example, contains nightly rates of 0 and 9,999 that no guest ever paid.
  • Text stand-ins: “unknown”, “not given”, “-” or “?” in a column that should hold names, emails or regions.
  • Values that can’t be right: a rating of 0 on a scale that starts at 1, or a date of birth of 1 January 1900 entered because the field was compulsory. The validation rules from the profiling lesson catch these; once confirmed, they are missing values in disguise.

The opposite trap matters just as much: a blank that is not missing. In Harborview’s bookings the children field is left empty when a party has no children, so a blank there means zero. Treating it as missing and filling it with the average number of children would invent children who never stayed. Before you touch a blank, find out what the person or system that created it meant.

Why a value is missing matters more than how many

Ana’s 4.38 is the average of the customers who chose to rate. Whether it describes all customers depends on why the others did not. The framework comes from the statistician Donald Rubin, whose 1976 paper defined data “missing at random” and set out when the reason for missingness can safely be ignored. The labels MCAR and MNAR (also written NMAR) came into use in later work, and three situations are now standard:

MCAR (missing completely at random)
Whether a value is missing has nothing to do with any data, recorded or not. Lantern example: a fault in the review email meant no rating requests went out for orders placed on two days in May, whoever placed them. The orders that lost their ratings are a random subset of all orders.
MAR (missing at random)
Whether a value is missing depends on other recorded variables, but within groups defined by them it is unrelated to the missing value itself. Lantern example: one-off buyers rate less often than subscribers, but among one-off buyers the satisfied and the dissatisfied are equally likely to skip.
MNAR (missing not at random)
Whether a value is missing depends on the missing value itself, even after allowing for everything recorded. Lantern example: customers whose beans arrived stale are the least likely to rate, and nothing in the export records which deliveries were stale.

The names are a famous source of confusion. “Missing at random” does not mean haphazard: it means random once you take the recorded variables into account. Data that are MAR can be badly unbalanced, as Lantern’s are.

Lantern’s ratings for one month of online orders (fictional)
Customer typeOrdersRatedShare ratedAverage of ratings given
Subscription1209075%4.6
One-off802025%3.4
All orders20011055%4.38

4.38 = (90 × 4.6 + 20 × 3.4) ÷ 110. The spreadsheet skipped the 90 blank cells.

Skipping the blanks weights each group by how many ratings it gave, not by how many orders it placed. Subscribers place 60% of the orders but supply 90 of the 110 ratings (82%), so the average leans towards their higher scores. If the ratings are MAR, so that the one-off buyers who skipped are like the one-off buyers who rated, a fair estimate weights each group by its orders: (120×4.6+80×3.4)÷200=4.12(120 \times 4.6 + 80 \times 3.4) \div 200 = 4.12. Ignoring the blanks overstated the rating by about a quarter of a star.

In depth

Rubin’s definitions, a little more precisely

Picture a second table the same shape as your data, holding 1 where a value is missing and 0 where it is present. Call its entries RR. Split the data values into those you have, YobsY_{\text{obs}}, and those you don’t, YmisY_{\text{mis}}. The three mechanisms say what the probability of a gap is allowed to depend on:

MCAR:Pr⁡(R=1∣Yobs,Ymis)=Pr⁡(R=1)MAR:Pr⁡(R=1∣Yobs,Ymis)=Pr⁡(R=1∣Yobs)MNAR:Pr⁡(R=1∣Yobs,Ymis) still depends on Ymis\begin{aligned} \text{MCAR:}&\quad \Pr(R = 1 \mid Y_{\text{obs}}, Y_{\text{mis}}) = \Pr(R = 1)\\ \text{MAR:}&\quad \Pr(R = 1 \mid Y_{\text{obs}}, Y_{\text{mis}}) = \Pr(R = 1 \mid Y_{\text{obs}})\\ \text{MNAR:}&\quad \Pr(R = 1 \mid Y_{\text{obs}}, Y_{\text{mis}}) \text{ still depends on } Y_{\text{mis}} \end{aligned}

Rubin’s 1976 result is that, under MAR (and a technical condition that the parameters of the missingness process are separate from those of the data), likelihood-based and Bayesian analyses can ignore the missingness process. In practice the result helps only if the analysis actually uses the recorded variables that explain the gaps. At Lantern, the ratings are plausibly MAR given subscription status; an analysis that ignores subscription status is back to the biased 4.38.

What you can check is limited but useful. Compare the rows with a missing value against the rows without on variables you do have: the share of subscribers, the order total, the region, the month. Clear differences rule out MCAR and point to the variables an analysis must include. Similar profiles are consistent with MCAR but don’t prove it, because the gaps may depend on something unrecorded.

Deletion

Listwise deletion, also called complete-case analysis, drops every row with a missing value in any variable the analysis uses. For a single column it is what a spreadsheet’s AVERAGE and SQL’s AVG do automatically: they skip blanks and NULLs. Under MCAR the remaining rows are a random sample of all rows, so means, variances and regression coefficients stay unbiased; the price is precision, because fewer rows are left. Under MAR and MNAR it can be biased, as Lantern’s 4.38 shows. It also wastes good data: if each of five variables is missing in a different 10% of rows, up to half the rows disappear.

Pairwise deletion, or available-case analysis, uses every row that has the values a particular statistic needs. The correlation between rating and order total uses the rows that have both; the correlation between order total and quantity uses a different, larger set. More data survive, but each statistic rests on different rows, so the results can contradict one another: a correlation matrix built this way may be one that no single dataset could produce, which breaks methods such as regression that need a consistent matrix. Like listwise deletion, it is biased when the data are not MCAR.

Single imputation

Imputation means filling each missing value with a plausible substitute so that every row can be used. The common single-imputation methods are:

  • Mean or median of the observed values in the column (mean imputation; use the median when the column is skewed).
  • Mode, the most frequent value, for categories such as region or product.
  • Group-wise mean, median or mode: the statistic computed within groups defined by a recorded variable, such as subscribers and one-off buyers. This is the simplest way to act on an MAR assumption.
  • A constant or a new category: 0 where a blank really means zero, or an explicit “Unknown” level for a missing region. For categories, “Unknown” is often the most honest fill because it doesn’t pretend to know.
  • A prediction from other columns, by regression or from the most similar complete rows (nearest neighbours).

All of them share one flaw: the filled values are then treated as if they had been observed. That has three costs.

Less spread. A value imputed at the mean sits exactly on the mean, so it adds nothing to the sum of squared deviations while adding one to the count. With nn observed values whose sample standard deviation is ss, filling mm gaps with the mean leaves the mean unchanged and shrinks the standard deviation to:

safter=sn−1n+m−1s_{\text{after}} = s\sqrt{\dfrac{n - 1}{n + m - 1}}

Take ten Northfield University students, six of whom recorded their weekly study hours: 4, 8, 10, 12, 14 and 18. Their mean is 11 and their sample standard deviation is 118÷5=4.86\sqrt{118 \div 5} = 4.86 hours. Fill the four gaps with 11 and the mean is still 11, but the standard deviation becomes 118÷9=3.62\sqrt{118 \div 9} = 3.62, a quarter smaller, although nothing about the students has changed. Every later calculation that uses the spread (a confidence interval, a standard error, a z-score) becomes overconfident.

Weaker relationships. The same ten students all have a recorded GPA. In the six complete rows, hours and GPA move closely together; after mean imputation the relationship looks much weaker.

Northfield study hours and GPA for ten students (fictional)
StudentHours recordedHours after mean imputationGPA
S01442.6
S02882.7
S0310103.2
S0412123.0
S0514143.5
S0618183.6
S07—112.6
S08—113.8
S09—112.9
S10—113.5

Correlation between hours and GPA: 0.92 in the six complete rows; 0.64 after mean imputation.

The reason is visible in the correlation formula. Its numerator adds up (hours − mean hours) × (GPA − mean GPA) across rows, and an imputed row contributes nothing because its hours sit exactly at the mean: the sum is 9.2 with or without the four filled rows. Its denominator, though, includes the spread of GPA, and the four extra students add to that spread (the sum of squared GPA deviations rises from 0.84 to 1.76). Same numerator, bigger denominator: 9.2÷118×0.84=0.929.2 \div \sqrt{118 \times 0.84} = 0.92 becomes 9.2÷118×1.764=0.649.2 \div \sqrt{118 \times 1.764} = 0.64. Any model fitted to mean-imputed data will understate how strongly study hours relate to grades.

Bias. Mean imputation leaves the mean exactly where the observed values put it, so under MAR and MNAR it carries the same bias as deletion: Lantern’s 4.38 does not move when you fill the blanks with 4.38. Group-wise imputation removes the bias under MAR when the groups capture what drives the missingness (fill subscribers’ blanks with 4.6 and one-off buyers’ with 3.4 and the mean becomes 4.12), but no fill rule computed from the observed data removes bias under MNAR. Regression imputation has the opposite problem to mean imputation: every filled value lies exactly on the fitted line, so relationships look stronger than they are.

The missing-value indicator

A missing-value indicator is a new 0/1 column, such as rating_missing, that records where a value was missing before you filled it. Keep one whenever you impute. It preserves the audit trail, so the filled rows can be excluded or checked later, and it lets a predictive model use the fact of missingness itself: at Lantern, a customer who never rates may be one who is drifting away. The scikit-learn documentation puts it plainly: “When using imputation, preserving the information about which values had been missing can be informative.”

The indicator is a tool for prediction and record-keeping, not a cure for bias. When the goal is to estimate the effect of one variable on another, the old trick of filling gaps with a constant and adding the indicator to a regression can be badly biased even when the data are MCAR (van Buuren, section 1.3.7).

Model-based and multiple imputation

Better methods use the other columns to predict each missing value and then put the uncertainty back. Multiple imputation, developed by Donald Rubin in the 1970s and set out in his 1987 book, works in three stages. It creates mm completed copies of the dataset, each filling the gaps with different plausible values drawn from a model of the data; it runs the analysis separately on every copy; and it pools the results with what are now called Rubin’s rules. The pooled estimate is the average across copies, and its variance combines the average within-copy variance with the between-copy variance, inflated by (1+1/m)(1 + 1/m) to allow for using a finite number of copies.

The disagreement between copies is the honest measure of how much the missing values could matter, which is exactly what single imputation throws away. Multiple imputation gives valid results under MAR when the imputation model includes the variables that drive the missingness. Under MNAR it needs extra assumptions, usually explored with what-if analyses such as “suppose non-raters are half a star less satisfied than raters”. In software it is available in R’s mice package; scikit-learn’s IterativeImputer (still labelled experimental) produces one completed copy per run, and repeated runs with sample_posterior=True and different random seeds give multiple imputations.

Imputing before modelling: training data only

When the cleaned data feed a predictive model that will be tested on held-out rows, compute every fill value (the mean, the median, the group modes, the parameters of an imputation model) from the training rows only, then apply those same values to the test rows. If the test rows help decide the fill values, information from the test data leaks into training and the model’s test score becomes optimistic. scikit-learn’s guide to common pitfalls lists SimpleImputer among the transformations this applies to, and gives the general rule: never call fit on the test data. The scaling lesson in module 4 treats leakage in full.

In a spreadsheet, SQL or pandas

  • Spreadsheet: AVERAGE skips empty cells but includes zeros, so a 0 placeholder silently drags an average down while a blank does not. COUNTBLANK counts the gaps in a range.
  • SQL: aggregate functions such as AVG ignore NULL. COUNT(rating) counts non-missing values and COUNT(*) counts rows, so their difference is the number missing. COALESCE(children, 0) replaces NULL with 0, which is right only where a blank really means zero.
  • pandas: pd.read_csv(path, na_values=['unknown', -999]) turns placeholders into missing values as the file loads (empty cells, NaN, N/A, NULL and other common markers are recognised by default); df.rating.isna().mean() gives the share missing; df.groupby('subscription').rating.transform('mean') produces group-wise fill values.

Formulas

Standard deviation after mean imputation

safter=sn−1n+m−1s_{\text{after}} = s\sqrt{\dfrac{n - 1}{n + m - 1}}
ss
Sample standard deviation of the observed values (dividing by n − 1)units of the variable
nn
Number of observed values
mm
Number of missing values filled with the observed mean

Assumes. Every gap is filled with the mean of the observed values; the mean itself is unchanged.

The square-root factor is always below 1 when m > 0, so the spread is always understated.

Group-weighted mean (group-wise imputation)

μ^=∑gNg yˉg∑gNg\hat{\mu} = \dfrac{\sum_g N_g\,\bar{y}_g}{\sum_g N_g}
NgN_g
Number of rows in group g, including those with a missing valuerows
yˉg\bar{y}_g
Mean of the observed values in group gunits of the variable

Assumes. Within each group, the rows with a missing value are like the rows without (MAR given the grouping variable).

Identical to filling each gap with its group’s mean and averaging all rows.

Pooling multiple imputations (Rubin’s rules)

Qˉ=1m∑j=1mQj,T=Uˉ+(1+1m)B\bar{Q} = \dfrac{1}{m}\sum_{j=1}^{m} Q_j, \qquad T = \bar{U} + \left(1 + \dfrac{1}{m}\right)B
QjQ_j
The estimate (for example a mean or a coefficient) from completed dataset junits of the estimate
mm
Number of completed datasets
Uˉ\bar{U}
Average of the squared standard errors across the m analyses (within-imputation variance)squared units
BB
Sample variance of the m estimates (between-imputation variance)squared units
TT
Total variance of the pooled estimate; its square root is the standard errorsquared units

Assumes. The imputations are drawn from a model that reflects the uncertainty about the missing values; valid under MAR when the model includes the variables that drive missingness.

Worked examples

A first example: What mean imputation does to the mean and the spread

Fictional figures

An online clothing retailer recorded delivery times for five of eight orders: 2, 3, 3, 4 and 8 days. The other three are blank because a courier’s tracking feed failed. Fill the blanks with the mean. What happens to the mean and to the sample standard deviation?

  1. Mean of the observed values: (2+3+3+4+8)÷5=20÷5=4(2 + 3 + 3 + 4 + 8) \div 5 = 20 \div 5 = 4 days.
  2. Squared deviations from 4: (−2)2+(−1)2+(−1)2+02+42=4+1+1+0+16=22(-2)^2 + (-1)^2 + (-1)^2 + 0^2 + 4^2 = 4 + 1 + 1 + 0 + 16 = 22. Sample variance 22÷4=5.522 \div 4 = 5.5, so s=5.5=2.35s = \sqrt{5.5} = 2.35 days.
  3. Fill the three blanks with 4. The sum becomes 20+3×4=3220 + 3 \times 4 = 32 over 8 orders, so the mean is still 4.
  4. Each filled value has a deviation of 0, so the sum of squared deviations stays 22, but it is now divided by 8−1=78 - 1 = 7: variance 22÷7=3.1422 \div 7 = 3.14, s=1.77s = 1.77 days.
  5. Check with the formula: 2.35×4÷7=2.35×0.756=1.772.35 \times \sqrt{4 \div 7} = 2.35 \times 0.756 = 1.77. The spread fell by about 24%.

Answer. The mean stays at 4 days; the standard deviation falls from 2.35 to 1.77 days.

What it means. Delivery times now look more predictable than they are. If the retailer promised “delivered within mean + 2 SD”, the imputed data would suggest 7.5 days instead of 8.7, and the promise would be broken more often than planned. The courier failure is plausibly MCAR only if that courier’s deliveries are typical of all deliveries (no faster or slower, no different routes); if they are, deleting the three rows would have kept an unbiased mean and an honest spread, just from fewer orders.

A harder example: Lantern’s rating: deletion, group-wise imputation and a what-if

Fictional figures

Twelve Lantern orders from one week, with ratings (1–5 stars):
Subscription orders: 5, 4, 5, 4, blank, 5.
One-off orders: 3, blank, blank, 4, blank, blank.
Estimate the average rating of all twelve orders (a) by ignoring the blanks, (b) assuming the ratings are MAR given customer type, and (c) assuming that within each group the customers who didn’t rate would have given half a star less than those who did.

  1. Count the gaps by group: 1 of 6 subscription orders and 4 of 6 one-off orders are blank. The gaps depend on a recorded variable, so the data are not MCAR.
  2. (a) Ignore the blanks (listwise deletion): (5+4+5+4+5+3+4)÷7=30÷7=4.29(5 + 4 + 5 + 4 + 5 + 3 + 4) \div 7 = 30 \div 7 = 4.29. Subscribers supply 5 of the 7 ratings although they place half the orders.
  3. (b) Group means of the ratings given: subscribers 23÷5=4.623 \div 5 = 4.6; one-off buyers 7÷2=3.57 \div 2 = 3.5. Under MAR, fill each gap with its group’s mean, which is the same as weighting each group by its orders: (6×4.6+6×3.5)÷12=48.6÷12=4.05(6 \times 4.6 + 6 \times 3.5) \div 12 = 48.6 \div 12 = 4.05.
  4. (c) What-if: fill the subscriber gap with 4.6−0.5=4.14.6 - 0.5 = 4.1 and each one-off gap with 3.5−0.5=3.03.5 - 0.5 = 3.0. Total 23+4.1+7+4×3.0=46.123 + 4.1 + 7 + 4 \times 3.0 = 46.1, so the average is 46.1÷12=3.8446.1 \div 12 = 3.84.

Answer. Ignoring blanks gives 4.29; group-wise imputation under MAR gives 4.05; the MNAR what-if gives 3.84.

What it means. Deletion overstates the rating because the happier group answers more. Group-wise imputation corrects that, but only if non-raters resemble raters of the same type, which no test can confirm. Reporting “about 3.8 to 4.1 stars, depending on how satisfied non-raters are” is more honest than any single number, and the cheapest real fix is to collect more ratings from one-off buyers.

Applied: a business decision: Filling ratings for a model without leaking test data

Fictional figures

Lantern is building a model to predict which one-off buyers will take out a subscription. Rating is one input. Of twelve orders, eight are for training, with ratings 5, 3, blank, 4, 4, blank, 2 and 5, and four are held back for testing, with ratings blank, 1, 2 and blank. The analyst wants to fill the blanks with the median. Which median, and what else should the cleaned data contain?

  1. Training ratings that exist, sorted: 2, 3, 4, 4, 5, 5. With six values the median is the average of the 3rd and 4th: (4+4)÷2=4(4 + 4) \div 2 = 4.
  2. Fill all four blanks, the two in training and the two in testing, with this training median of 4. The test rows are treated exactly as new customers will be: with a value learned before they arrived.
  3. The tempting alternative pools all eight observed ratings (1, 2, 2, 3, 4, 4, 5, 5) and gets (3+4)÷2=3.5(3 + 4) \div 2 = 3.5. That uses the test rows’ ratings to decide how training rows are filled, which is leakage.
  4. Add the indicator rating_missing: 1 for the four filled rows, 0 for the rest, so the model can learn whether not rating predicts not subscribing.

Answer. Fill every blank with the training median, 4, and keep a rating_missing indicator column.

What it means. With twelve rows the difference between 4 and 3.5 looks small, but the principle scales: whenever a statistic computed on the test rows shapes the training data, the test score stops being a fair preview of performance on customers the model has never seen. Saving the fill value (4) with the model also means next month’s orders are cleaned the same way.

Explore

Lantern’s order export has missing ratings and emails. It covers four months, not Ana’s one fictional month, so don’t expect it to match the 200 orders and 90 blanks above: 80 of its 240 ratings are blank. Inspect the rating column, then compare the treatments: drop the incomplete rows, fill the gaps with the overall mean, fill them with each subscription group’s mean, and flag them. Watch the row count, the mean rating and its spread after each step: dropping changes only the row count, the overall mean changes only the spread, the group means move the mean (one-off buyers rate less often and lower), and the flag leaves a record of what was missing.

Loading the interactive…

Change how many values are missing and what they would have been. The mean after imputation never moves and the spread always shrinks; the bias depends on the true mean of the missing values, which in real data you never get to see.

Loading the interactive…

Common mistakes

  • “A blank is just a blank.”

    Blanks, NA, 0, −999 and “unknown” can all mean missing, while some blanks mean zero (Harborview’s empty children field). Averaging a −999 wrecks a mean; filling a blank that meant zero invents data. Find out what each code meant to whoever recorded it, then convert real gaps to one missing marker and meaningful blanks to their value.

  • “Filling the gaps with the mean removes the bias.”

    Mean imputation keeps the mean of the observed values, so it carries exactly the bias of ignoring the gaps. Lantern’s 4.38 stays 4.38. Only methods that use the variables driving the missingness, such as group-wise or multiple imputation, can reduce bias, and only under MAR.

  • “After imputing, I have the full sample, so my statistics are as precise as a complete dataset’s.”

    Imputed values carry no new information. Treating them as observed shrinks standard deviations and standard errors, makes confidence intervals too narrow and weakens correlations. Report how many values were imputed, keep an indicator, and use multiple imputation when the uncertainty matters.

  • “The rows with gaps look like the others, so the data are missing completely at random.”

    Similar profiles on recorded variables are consistent with MCAR but cannot prove it: the gaps may depend on the missing values themselves (MNAR). Differences, on the other hand, do rule MCAR out. Decide between MAR and MNAR from how the data were collected, and test how much the answer changes under a what-if.

  • “I’ll impute first and split into training and test sets afterwards.”

    Fill values computed on all rows use information from the test set, so the test score is no longer a fair estimate of performance on new data. Split first, compute fill values on the training rows, apply them to both.

Guided practice

Work through these with hints when you need them. Every hint and every worked solution is there to be used.

Loading four questions…

On your own

No hints this time. Answer, check, and read the feedback; the solution appears once you have answered or if you ask for it. Your first answers count toward mastery.

Loading six questions…

In practice

Ana now has three numbers for Lantern’s rating: 4.38 from the ratings given, 4.12 if non-raters resemble raters of the same customer type, and about 3.9 if non-raters are half a star less satisfied (the same what-if as in the worked example, applied to the month’s 200 orders). She decides the home page will say “4.4 stars from 110 customer ratings”, which is true and describes exactly what it counts, while the internal dashboard tracks the weighted figure, because that is the one that reflects all customers. She also changes the process: one-off buyers now get a single reminder email, which reduces the gaps instead of modelling around them. Collecting better data is often the cheapest fix for missing data.

The same reasoning runs through other industries. A Harborview revenue manager finds that blank children fields mean no children, fills them with 0 and writes that down. A Northfield analyst comparing study hours across years notices that hours are missing more often in some years than others; comparing raw averages across years would mix differences in students with differences in who answered, so the analyst compares years using group-wise estimates, shows the share missing beside each figure, and asks the registry why the survey response fell. An airline analysing post-flight surveys in which business-class passengers answer more often than economy passengers should weight the responses by cabin for the same reason.

For predictive work the rules are mechanical once learned. Lantern’s subscription model fills missing ratings with the training median, keeps a rating_missing indicator, and stores the fill values with the model so that new orders are cleaned identically. When the model is later used to estimate how much ratings matter, rather than just to predict, the analyst switches to multiple imputation so that the uncertainty from the gaps shows up in the confidence intervals.

A decision guide

  1. Find. Convert placeholders, text stand-ins and confirmed impossible values to one missing marker; leave blanks that mean zero as zero, and document both.
  2. Measure. Count the share missing in each column, then break it down by the groups that matter (customer type, region, year, channel).
  3. Explain. Ask the people who collect the data why values go missing, and decide which mechanism is plausible. Differences between groups rule out MCAR; nothing in the data rules out MNAR.
  4. Choose by purpose. To describe a group: delete if MCAR is plausible and few rows are lost; weight or impute by group if MAR; report a range if MNAR is plausible. To build a model: impute with training-set values, add indicators, and use multiple imputation when you need honest uncertainty.
  5. Record. Write down what you treated as missing, what you did, and how much the key numbers changed. A data quality report (the last lesson of the course) collects these decisions.

Knowledge check

Six questions, one attempt each, no hints. Score 80% or more to complete the lesson; you can take it again at any time.

Loading six questions…

Summary

  • Missing values hide as blanks, NA codes, placeholders such as 0 or −999, text such as “unknown” and impossible values; some blanks mean zero and must not be treated as missing.
  • MCAR: missingness unrelated to any data. MAR: related only to recorded variables. MNAR: related to the missing values themselves. Data can rule out MCAR but cannot separate MAR from MNAR.
  • Ignoring gaps (listwise deletion) is unbiased under MCAR but can be biased otherwise: Lantern’s 4.38 overstates the 4.12 estimated under MAR because satisfied subscribers rate more often.
  • Mean imputation keeps the observed mean (and its bias), shrinks the standard deviation by the factor √((n − 1) ÷ (n + m − 1)), and weakens correlations.
  • Group-wise imputation can remove bias under MAR; multiple imputation also keeps the uncertainty, pooling m completed datasets with Rubin’s rules.
  • Keep a missing-value indicator whenever you impute; for models, compute fill values on the training rows only.

Key formulas

Terms introduced

Missing value
A cell where a value should exist but was not recorded, whether it appears as a blank, a code such as NA or −999, a text stand-in such as “unknown”, or an impossible value.
MCAR
Missing completely at random: whether a value is missing is unrelated to any data, recorded or not.
MAR
Missing at random: whether a value is missing depends only on recorded variables; within groups defined by them it is unrelated to the missing value itself.
MNAR
Missing not at random: whether a value is missing depends on the missing value itself, even after allowing for the recorded variables.
Listwise deletion
Dropping every row that has a missing value in any variable an analysis uses; also called complete-case analysis.
Pairwise deletion
Computing each statistic from all rows that have the values it needs, so different statistics use different rows; also called available-case analysis.
Imputation
Replacing a missing value with a substitute value, such as a mean, a group median, a category such as “Unknown” or a model’s prediction.
Mean imputation
Filling every missing value in a column with the mean of the observed values; it keeps the mean, shrinks the spread and weakens relationships.
Missing-value indicator
A 0/1 column that records which values were missing before imputation, kept for auditing and as a possible model input.
Multiple imputation
Creating several completed copies of a dataset with different plausible fills, analysing each, and pooling the results so that the uncertainty about the missing values is reflected in the answer.

Sources

  1. Rubin, D. B. (1976). Inference and missing data. Biometrika, 63(3), 581–592. doi:10.1093/biomet/63.3.581. dash.harvard.edu/entities/publication/73120378-8764-6bd4-e05…
  2. Rubin, D. B. (1987). Multiple Imputation for Nonresponse in Surveys. New York: Wiley. ci.nii.ac.jp/ncid/BA00677174
  3. van Buuren, S. (2018). Flexible Imputation of Missing Data, 2nd edition, sections 1.2 “Concepts of MCAR, MAR and MNAR” and 1.3 “Ad-hoc solutions”. Boca Raton: CRC/Chapman & Hall. Free online. stefvanbuuren.name/fimd/sec-simplesolutions.html
  4. Molenberghs, G., Beunckens, C., Sotto, C. & Kenward, M. G. (2008). Every missingness not at random model has a missingness at random counterpart with equal fit. Journal of the Royal Statistical Society, Series B, 70(2), 371–388. researchonline.lshtm.ac.uk/id/eprint/7959
  5. scikit-learn developers. User Guide: “Imputation of missing values” (SimpleImputer, IterativeImputer, MissingIndicator). scikit-learn.org/stable/modules/impute
  6. scikit-learn developers. User Guide: “Common pitfalls and recommended practices”, section on data leakage during pre-processing. scikit-learn.org/stable/common_pitfalls.html