Missing data: deletion, imputation and honest flags, without fooling yourself
TL;DR
Difficulty: Advanced
How you handle a missing value is a decision about your business, and most tools make it for you by default.
- Find every form of empty first: NULLs, empty strings, placeholders, fake dates, zero defaults and rows that are not there at all.
- Separate not applicable and not yet known from truly unknown, and never fill the first two.
- Why values are missing decides which methods are safe. Data can rule out MCAR but never prove MAR.
- Fix at the source first. Never use a fake default such as zero or 1 January 1900.
- Deletion only for small, random gaps. Otherwise fill within groups or with a model, and use multiple imputation for honest standard errors.
- Keep the raw value, flag every fill, test the rules, and report the imputed share and a plausible range.
Every dataset has holes, and every tool quietly fills them its own way: SQL skips them, spreadsheets turn them into zeros, libraries fill them with the average. This chapter shows what each choice does to your averages, totals and uncertainty, worked through on one online shop's real kinds of gaps, and how to handle missing values so that nobody is fooled, least of all you.
An empty field is a decision waiting to be made
Every dataset has holes. A phone number nobody typed, a cost price the supplier never sent, a week of returns that did not arrive, a purchase that analytics never saw. The question is never whether you have missing data. It is what you do with it, and whether you notice what that choice does to your numbers.
Most tools make the choice for you, quietly. SQL skips empty values in an average. A spreadsheet treats a blank as zero in one formula and ignores it in the next. A machine learning library refuses to run until you fill every gap, so someone fills them with the average and moves on. Each of these is a decision about your business, made by a default.
This chapter walks through the whole toolkit: how to find every kind of empty, why data goes missing (the reason decides everything), what deleting rows does, what filling them does, how to fill time series, how multiple imputation puts the uncertainty back, and how to flag and report all of it so nobody is fooled, least of all you. The previous chapter, when to clean data and when to leave it alone, gave the decision framework. This one goes deep on the most common cleaning problem of all.
Example: three numbers on a Monday morning
Shannonside Home is the series' example: an online homeware shop in Limerick (shannonsidehome.example) with about 1,400 products, 1,980 orders a month and an average order value of €84. Niamh owns it. Callum is the developer and data engineer.
On one Monday, three numbers land on Niamh's desk. The marketing report says average order value was €82.66. The margin report says gross margin was 47.9%. The returns chart shows two weeks in January with zero returns. All three are wrong, and all three are wrong for the same reason: something was missing, and a default filled the gap without asking. By the end of this chapter you will see exactly how each one happened, and what the honest version looks like.
First find out what "missing" looks like in your data
Before you can handle missing values, you have to find them, and they hide in more forms than an empty cell. Here are the ones I check for in every dataset:
- NULL: the database's own marker for "no value". The only honest one.
- Empty strings: a text field containing nothing (''), which a database counts as a value.
- Whitespace only: a field holding nothing but spaces. It looks empty and is not.
- Placeholders: "n/a", "none", "unknown", "0", "00000", typed by people or tools to get past a required field.
- Sentinel values: a fake date such as 1 January 1900 or 1 January 1970, or a number such as 9999 or minus 1, used by an old system to mean "nothing".
- Defaults that look like data: a column that silently fills itself with 0 when nobody sends a value.
- Join induced gaps: a LEFT JOIN keeps every row of the left table and fills the columns of the right table with NULL wherever no partner row exists1. Those NULLs were never in either table.
- Missing rows: the whole record is absent, so nothing in the table even tells you a gap exists.
The last two are the most dangerous, because a profile of a single table will never show them. You only find them by comparing against something that knows the full count, which the profiling chapter covered in detail in finding out how dirty your data really is.
Example: Callum counts every kind of empty phone number
The shop stores phone numbers in spree_addresses.phone, a plain text column in Solidus2. The fixed known problem of the example: about 2% of orders have a missing or invalid phone number. Callum wants to know what "missing" actually means here, so he counts each form separately over last year's 23,760 orders (PostgreSQL):
-- PostgreSQL: every form of "empty" in the billing phone of completed orders
select
count(*) as orders,
count(*) filter (where a.phone is null) as phone_null,
count(*) filter (where a.phone = '') as phone_empty_string,
count(*) filter (where a.phone <> '' and btrim(a.phone) = '') as phone_whitespace_only,
count(*) filter (where lower(btrim(a.phone)) in ('0', '00000', 'none', 'n/a', 'na'))
as phone_placeholder,
count(*) filter (where a.phone is not null
and lower(btrim(a.phone)) not in ('0', '00000', 'none', 'n/a', 'na')
and length(regexp_replace(a.phone, '\D', '', 'g')) between 1 and 7)
as phone_too_short
from spree_orders o
join spree_addresses a on a.id = o.bill_address_id
where o.completed_at >= date '2025-01-01'
and o.completed_at < date '2026-01-01';
The filter (where ...) clause counts only the rows that match its condition3, so one pass over the table gives every number. The result:
| orders | phone_null | phone_empty_string | phone_whitespace_only | phone_placeholder | phone_too_short |
|---|---|---|---|---|---|
| 23,760 | 212 | 96 | 31 | 58 | 78 |
Add them up: 212 + 96 + 31 + 58 + 78 = 475 orders, which is 2.0% of 23,760. A naive check for NULL alone would have found 212, less than half. The other 263 look like data to every query that does not know better. Callum's first cleaning step is therefore not a fill at all: he turns all five forms into one honest NULL in the staging layer, so that every later step sees the same thing.
Example: the weight that says zero
Here is a subtler one. In the Solidus schema, spree_variants.weight is a decimal column with a default of 0.0, while height, width, depth and cost_price have no default and stay NULL when empty2. So when a supplier feed arrives without a weight, the shop does not store "unknown". It stores zero.
Shannonside has 2,610 variants. Callum finds 184 with a weight of exactly 0.00 kg. Six of them are gift vouchers sent by email, which genuinely weigh nothing. The other 178 are sofas, lamps and rugs whose weight was simply never sent. The 2,426 variants with a real weight average 2.45 kg.
The average the shipping report shows, with the fake zeros in it:
So the report says kg.
The honest average keeps the six real zeros and leaves out the 178 unknowns:
That is kg, and the naive figure is 6.8% too low. Every shipping cost estimate built on it is too low by the same share. The fix belongs at the source: a Rails migration that makes an unknown weight NULL instead of zero, using change_column_default with explicit from and to values so it can be reversed4. Here it is:
# db/migrate/20260105090000_make_unknown_variant_weight_null.rb
class MakeUnknownVariantWeightNull < ActiveRecord::Migration[8.0]
def change
change_column_default :spree_variants, :weight, from: 0.0, to: nil
end
end
Changing a default touches shipping calculators that may expect a number, so this goes in test first, with a test for a variant whose weight is unknown, like every change to the shop. The existing 178 fake zeros are then set to NULL by a one off, logged data fix, and the six gift vouchers keep their real zero.
Not every gap is missing: four kinds of empty
Before choosing any method, ask why the field is empty. Four very different situations produce the same blank:
| State | What it means | Shop example | What to do |
|---|---|---|---|
| Known | A real value exists | A phone number that dials | Use it |
| Not applicable | No value can exist, by design | A guest checkout has no account creation date | Never fill. Model it as its own state |
| Unknown | A value exists in the world, but you do not have it | A lamp's real weight | Fix at source, or handle with the methods in this chapter |
| Not yet known | The value will arrive later | A return the 3PL warehouse reports up to five days late | Wait, mark as provisional, and restate |
The first mistake I see in nearly every dataset is treating "not applicable" as "unknown". Statisticians call the first kind structural missingness: the gap is the correct answer. Filling it creates information that cannot exist.
Example: the customer called NULL
In Solidus, a guest checkout leaves spree_orders.user_id empty, because there is no account to point to2. At Shannonside, 31% of orders are guest orders (an invented share for the example), so about 7,366 of last year's 23,760.
Callum's colleague writes a quick query for the top customers by number of orders:
-- PostgreSQL: the naive "top customers" query
select user_id, count(*) as orders
from spree_orders
where completed_at >= date '2025-01-01' and completed_at < date '2026-01-01'
group by user_id
order by orders desc
limit 3;
| user_id | orders |
|---|---|
| NULL | 7,366 |
| 18,204 | 41 |
| 9,377 | 33 |
GROUP BY puts every NULL into one group, so the shop's "best customer" is nobody at all, with 7,366 orders. Filling the gap would be worse: give guests a fake user id of 0 and the same row reappears under a new name. The honest model makes the state explicit:
-- PostgreSQL: make the structural gap explicit instead of filling it
select
o.id,
o.user_id,
case when o.user_id is null then 'guest' else 'registered' end as checkout_type,
lower(btrim(o.email)) as email_normalised
from spree_orders o;
Guests are then counted by their normalised email, which is the start of the deduplication work in the next chapter on making sure one customer is one record. The "not yet known" state gets the same treatment. A return that the 3PL warehouse has not reported yet is not a missing return. Callum adds a return_status_as_of date to the returns model, so a report can say "returns up to 9 January are complete, later days are provisional".
Why data goes missing: MCAR, MAR and MNAR
Once you know a value is truly unknown, the next question decides which methods are safe: why is it missing? Donald Rubin gave the field its vocabulary in 1976, sorting every missing data problem into three classes by the process that causes the gaps5. In plain words:
- Missing completely at random (MCAR): the chance that a value is missing has nothing to do with any data, observed or not. Bad luck, like a scale whose battery died6.
- Missing at random (MAR): the chance of being missing depends only on things you have observed. Within groups you can see, the gaps are random.
- Missing not at random (MNAR): the chance of being missing depends on the missing value itself, or on something you have not recorded.
Formally, write for the indicator that a value was recorded () or not (), and split the data into the observed part and the missing part. If probability notation is new to you, Foundations: probability covers it from scratch.
Here is the response indicator, the values you have, the values you do not have, and the probability of given . MCAR says the missingness ignores everything. MAR says that once you know the observed data, the missing values tell you nothing more about whether a value went missing. MNAR is everything else.
Why this matters: almost every simple fix (deleting rows, filling with the average) is only safe under MCAR. Modern methods such as multiple imputation start from MAR. Under MNAR, no method can recover the truth from the data alone, and the honest answer is more data or a sensitivity analysis6.
Example: three gaps at Shannonside, three mechanisms
MCAR. On one Tuesday in March, the transfer job that fetches the 3PL warehouse's daily shipment file failed because of a network timeout, and nobody noticed for a week. The missing day has nothing to do with what was shipped that day. That gap is MCAR: it loses information, but it does not bend any average.
MAR. The 475 missing phone numbers are not spread evenly. Callum splits them by device, which the shop records for every order:
| Device | Orders | Phone missing | Missing rate |
|---|---|---|---|
| Desktop | 10,692 | 128 | 1.20% |
| Mobile | 13,068 | 347 | 2.66% |
| Total | 23,760 | 475 | 2.00% |
On mobile the phone field sits below the fold and is optional, so people skip it twice as often. If, within each device, the gaps are random, the data are MAR given device. Any analysis that involves phone numbers must then take device into account.
MNAR. The newsletter tool asks for a date of birth, optionally, for a birthday voucher. Callum suspects older subscribers give it less often. If that is true, the missingness depends on age itself, the very value that is missing. That is MNAR, and no amount of clever filling inside the newsletter data can fix it.
You can rule out MCAR, but you can never prove MAR
This is the part people get wrong, so it is worth being precise. Data can show you that missingness depends on something you observed, which rules out MCAR. Roderick Little published a formal test for exactly this in 19887. A simpler version for one field: compare the missing rate between two groups.
The two proportion z test (see Foundations: hypothesis tests) asks how many standard errors apart two rates are:
where and are the missing rates in the two groups, and the group sizes, and the missing rate of both groups together.
Example: is the phone gap MCAR?
Desktop: . Mobile: . Together: .
The denominator, the standard error of the difference:
So the denominator is . Then:
A value of is far beyond the usual threshold of about 2. Phone numbers are not MCAR. But notice what the test cannot do. It cannot tell Callum whether, within mobile orders, the people who skip the phone field differ in some unrecorded way from those who fill it in. Distinguishing MAR from MNAR needs knowledge from outside the data: how the form works, what customers say, a small follow up sample. The data alone will never settle it6.
Missing rows are a different problem from missing values
Survey statisticians separate two kinds of gap. Item missingness: the row exists, one value in it is empty. Unit missingness: the whole row is absent. They need different tools. You impute a missing value. You cannot impute a row you do not know exists. Instead you reweight the rows you have to a total you trust.
The best known unit gap in eCommerce data is analytics. The fixed problem of the example: GA4 shows about 15% fewer purchases than the shop, because of consent choices and blockers. The purchases are not empty rows in GA4. They are simply not there.
The simplest correction is a weight, the ratio of the true count to the observed count (see Foundations: ratios and rates):
where is the number of orders in the shop database and the number of purchase events GA4 recorded for the same period.
Example: weighting GA4 back up to the shop
In one month the shop recorded 1,980 orders and GA4 recorded 1,683 purchases, 15% fewer. The GA4 purchases average €85.75, so GA4 revenue is euro.
So each GA4 purchase stands for shop orders. Weighted GA4 revenue:
That gives euro. But the shop's true revenue is euro. The weighting overstates revenue by €3,465, because the 297 buyers GA4 never saw spent less on average: euro each. Weighting assumes the missing rows look like the observed ones, which is MCAR, or MAR within whatever groups you weight by. Here they did not.
The lesson for an engineer is short: when a source of truth exists, use it. The shop database knows every order, so revenue comes from the shop, and GA4 is used for what only GA4 knows, such as which pages people saw. The shop database as the source of truth shows how to send purchases from the server, and when analytics, ads and orders disagree shows how to reconcile the rest.
Deleting rows: listwise and pairwise deletion
The oldest approach is to leave out anything incomplete. Listwise deletion, also called complete case analysis, drops every row with a gap in any column the analysis uses. It is what SQL's AVG does for one column, since aggregate functions skip NULL inputs3, and what many statistics packages do by default for a whole model8.
Its honest strength: if the data are MCAR, listwise deletion gives unbiased means, variances and regression weights. Its weaknesses: it throws away information, and if the data are not MCAR, it biases almost everything8.
The waste compounds. If missingness in different columns is independent, the share of complete rows is the product of the shares present in each column (see Foundations: probability):
where is the number of columns the analysis uses and the missing rate of column .
Example: the model that lost 62% of its rows
Callum wants a model of what drives order value, with three inputs that have gaps: the routing key of the delivery Eircode (0.4% missing), the customer's age from the newsletter's date of birth (61% missing, because the field is optional) and the device (3% missing in the oldest orders).
Only of rows survive, so 62.3% are thrown away, and almost all of that comes from one optional field. And because the people who give their birth date are not a random subset (the MNAR suspicion above), the survivors are not even representative. The right move here is not a cleverer deletion. It is to ask whether age belongs in the model at all.
Pairwise deletion, also called available case analysis, tries to waste less: each statistic uses every row where its own inputs are present. A correlation between A and B uses the rows with both, a correlation between B and C uses a different set of rows. It sounds efficient, but the statistics now come from different subsets, the resulting correlation matrix can be mathematically impossible (not positive definite), and nobody can say which sample size the standard errors should use8. I use it for quick exploration only, never for a published number.
Example: the average that quietly dropped PayPal
Now the first wrong number from Monday morning. After a template change on the payment return page, GA4 purchase events from PayPal orders arrived without a value: ecommerce.purchase_revenue, the field the BigQuery export uses for purchase revenue9, was NULL for 200 of the month's 1,683 purchases (an invented fault for the example).
The 1,683 purchases split like this:
| Payment | Purchases | Average value | Revenue |
|---|---|---|---|
| Card and other | 1,183 | €79.80 | €94,403.40 |
| PayPal | 500 | €93.94 | €46,970.00 |
| All | 1,683 | €84.00 | €141,373.40 |
But 200 PayPal values are missing, so only 300 PayPal purchases carry a value. The marketing analyst's query (BigQuery):
-- BigQuery: average order value from the GA4 export, the naive way
select avg(ecommerce.purchase_revenue) as aov
from `shannonside-analytics.analytics_123456789.events_*`
where event_name = 'purchase'
and _table_suffix between '20260101' and '20260131';
AVG skips the NULLs, so this is listwise deletion:
So the report says euro, not 84.00. The missing values were all PayPal purchases, which are larger than average, so dropping them pulled the average down. That is the textbook MAR case: missingness depends on an observed variable, payment type, and deletion ignores it.
Fake defaults: why "unknown" beats zero, 1900 and "UK"
The opposite reflex to deleting is to fill every gap with something that looks harmless. Zero for a number, 1 January 1900 for a date, the home country for a country. These are not neutral. They are claims, and usually false ones.
The same analyst, told that AVG skipped some rows, "fixes" it:
-- BigQuery: the fake default
select avg(coalesce(ecommerce.purchase_revenue, 0)) as aov
from `shannonside-analytics.analytics_123456789.events_*`
where event_name = 'purchase'
and _table_suffix between '20260101' and '20260131';
COALESCE returns its first argument that is not NULL10, so every missing value becomes 0:
Now average order value reads euro, 13% below the truth, because 200 real purchases are counted as free. The "fix" made it worse.
Example: the customers born on 1 January 1900
The newsletter tool exports a date of birth for 9,120 of its 38,000 subscribers. Callum notices 410 of them on exactly 1 January 1900: the signup form used to prefill that date, and people who did not want to share left it. The 8,710 real dates give an average age of 41.3. The fake date makes those 410 people 126 years old in 2026:
The average subscriber appears years old instead of 41.3, and a campaign aimed at "the over 45s" is built on a ghost. The rule I apply everywhere: an unknown value is stored as NULL, or as an explicit "unknown" category, never as a value that could be real. The same goes for country. Defaulting a missing country to Ireland quietly moves orders from the UK and further afield into Irish VAT, which is why the chapter on making the same thing look the same everywhere maps every country spelling to a code and sends the unmappable ones to an "unknown" bucket rather than a guess.
Mean and median imputation, and the variance they remove
Imputation means replacing a missing value with an estimate. The simplest estimate is the average of the observed values (mean imputation) or their middle value (median imputation, more robust for skewed amounts such as money, see Foundations: median and mode).
Under MCAR, mean imputation leaves the mean unchanged. But it damages everything else. Every imputed value sits exactly on the mean, so it adds nothing to the spread, while the row count goes up. The variance shrinks by a predictable factor (see Foundations: spread):
where is the variance of the observed values, the variance after mean imputation, the number of observed values and the total number of rows. The reason is simple: the sum of squared deviations stays the same, because each imputed value deviates by zero, but you now divide it by instead of .
That smaller spread then flows into every uncertainty calculation. The standard error of a mean (see Foundations: confidence intervals) is
where is the standard deviation and the number of values. Mean imputation shrinks and inflates at the same time, so the interval narrows twice, although you learned nothing new.
It also weakens relationships. If you mean impute and leave complete, the covariance between them shrinks by the same factor as the variance of , and the correlation (see Foundations: correlation) shrinks by its square root, approximately:
where is the correlation between the two variables in the complete rows and the correlation after imputation. Stef van Buuren's free textbook, Flexible Imputation of Missing Data, shows the same effect on a real dataset: the standard deviation of the imputed variable falls and its correlation with another variable drops8.
Example: what mean imputation does to Shannonside's order values
Take the 1,483 GA4 purchases that have a value. Their standard deviation is €54.60 (invented for the example). Callum fills the 200 gaps with the observed mean of €82.66, so and .
The shrink factor:
So the variance keeps of its size. The standard deviation keeps the square root of that, :
So euro. Now the standard errors, before and after:
That is euro for the observed values alone. After mean imputation:
The standard error falls from to . A 95% interval is about 1.96 standard errors either side, so it narrows from plus or minus €2.78 to plus or minus €2.45, about 12% tighter. The data did not get better. The method just pretended 200 guesses were measurements. And the centre is still wrong: €82.66, because the mean was taken from the observed rows, which are missing the larger PayPal purchases. If basket size and order value correlated at 0.62 in the complete rows, after mean imputation the correlation reads about . Showing uncertainty honestly explains why an interval that is too narrow is worse than none.
Conditional imputation: fill within the groups that explain the gap
If the data are MAR, the gaps are random within groups defined by observed variables. So fill within those groups. Instead of one average for everyone, use the average (or median) of the rows that share the relevant observed characteristics. When each gap borrows a real value from a similar complete row instead of a group average, the method is known as hot deck imputation11.
Example: average order value under five strategies
Back to the PayPal gap. The missingness depends on payment type, which GA4 records in a custom parameter Callum sends with every purchase. Within PayPal purchases, the 200 missing values were lost because of the template, not because of anything about the orders themselves, so MAR given payment type is plausible.
Filling each missing PayPal value with the average of the observed PayPal purchases, €93.94:
That recovers euro, the true figure. All five strategies side by side:
The group mean only worked because the right group was observed. Had the missingness depended on something GA4 did not record, no grouping would have saved it. And even here, the best fix of all was at the source: Callum repaired the return page template and replaced the GA4 revenue figure with the shop's own, which never had a gap.
Example: cost prices by category, and the margin report
The second wrong number from Monday: gross margin 47.9%. Gross margin is revenue minus the cost of the goods sold, as a share of revenue (see Foundations: percentages):
where revenue is the product revenue excluding VAT and cost is the sum of the variants' cost prices times the quantities sold, so is a share between 0 and 1.
spree_variants.cost_price is empty for 214 of Shannonside's 2,610 variants (8.2%), mostly lighting products added last quarter from a new supplier whose feed has no cost column. Last month's product revenue excluding VAT was €130,000. Lines whose variant has a cost price brought €117,900 at a cost of €67,790. Lines without a cost price brought €12,100.
Four ways to handle it, each worked through:
Treat a missing cost as zero. This is what a SUM over a nullable column with COALESCE to zero does, and what the margin report did.
A margin of , because €12,100 of sales are treated as pure profit.
Delete the lines without cost. Margin of the known lines only:
A rate of , but on only 91% of revenue, and the margin in euro, €50,110, ignores the lighting sales entirely.
Fill with the category's median cost ratio. For each category, Callum computes the median of cost divided by price across variants that have both. For lighting it is 0.61. The imputed cost of the €12,100 is euro:
A margin of .
The truth, from the supplier's invoices six weeks later: the lighting lines cost €7,870.
The real margin was .
The category fill got within 0.4 points. Deletion was not far off as a rate, but useless in euro. The zero was six points out, enough to approve a discount campaign the shop could not afford. Here is the conditional fill in SQL, with the source of every value kept alongside it (PostgreSQL):
-- PostgreSQL: fill missing cost prices with the category median cost ratio, and say so
with ratios as (
select
p.category_id,
percentile_cont(0.5) within group (order by v.cost_price / pr.amount) as median_cost_ratio,
count(*) as donors
from spree_variants v
join products_with_category p on p.product_id = v.product_id -- a model mapping each product to one category
join spree_prices pr on pr.variant_id = v.id and pr.currency = 'EUR'
and pr.deleted_at is null and pr.country_iso is null
where v.cost_price is not null and pr.amount > 0
group by p.category_id
)
select
v.id as variant_id,
v.cost_price as cost_price_raw,
coalesce(v.cost_price, round(pr.amount * r.median_cost_ratio, 2)) as cost_price_filled,
case
when v.cost_price is not null then 'supplier'
when r.median_cost_ratio is not null and r.donors >= 20 then 'category_median_ratio'
else 'unknown'
end as cost_price_source
from spree_variants v
join products_with_category p on p.product_id = v.product_id
join spree_prices pr on pr.variant_id = v.id and pr.currency = 'EUR'
and pr.deleted_at is null and pr.country_iso is null
left join ratios r on r.category_id = p.category_id;
Three details matter. The raw value survives next to the filled one. A category with fewer than 20 donors gets no fill at all, because a median of four rows is a guess dressed as a statistic. And cost_price_source travels with every row into every report. (Solidus stores prices in spree_prices and links products to categories through taxons, so products_with_category stands for a small model that picks one category per product. Solidus tax rates can be set as included in the price, so check whether your prices include VAT before dividing2.)
Model based imputation: regression, neighbours and predictive mean matching
When several observed variables explain a gap, a model can use all of them at once. Regression imputation fits a model on the complete rows and fills each gap with the prediction. It sounds like the grown up version of the group mean, and van Buuren calls it probably the most dangerous of the simple methods: the filled values sit exactly on the regression line, so relationships look stronger than they are, the spread is too small, and the imputations are "too good to be true"8.
Three refinements fix most of that:
- Stochastic regression imputation adds a random draw from the model's residuals to each prediction, so the spread comes back8.
- Nearest neighbour imputation fills a gap with the average of the most similar complete rows.
scikit-learn'sKNNImputerdoes this12. - Predictive mean matching (PMM) uses the model only to find donors: for each gap it picks a few complete rows whose predictions are closest, draws one of them at random and copies that row's real observed value. Imputations are always values that actually occurred, so you never get a negative price or a lamp weighing 0.3 grams11.
For money, sizes and counts, I reach for PMM first. It is robust when the model is not quite right, which it never is.
Example: imputing cost ratios with a model in Python
Callum has more than category to go on: the supplier, the selling price and the product's weight all relate to the cost ratio. He uses scikit-learn's IterativeImputer, which models each column with gaps as a function of the others and cycles until the fills settle12. It is still marked experimental, so it needs an explicit enabling import:
# Python 3, pandas and scikit-learn: model based imputation with a flag kept
import pandas as pd
from sklearn.experimental import enable_iterative_imputer # noqa: F401, required while experimental
from sklearn.impute import IterativeImputer
variants = pd.read_parquet("clean/variants_features.parquet")
features = ["cost_ratio", "price_ex_vat", "weight_kg", "supplier_code", "category_code"]
X = variants[features]
flag = X["cost_ratio"].isna() # remember what was missing before filling
imputer = IterativeImputer(max_iter=10, random_state=0)
filled = pd.DataFrame(imputer.fit_transform(X), columns=features, index=X.index)
variants["cost_ratio_filled"] = filled["cost_ratio"].clip(lower=0.05, upper=0.95)
variants["cost_ratio_imputed"] = flag
print(variants.loc[flag, ["sku", "cost_ratio_filled"]].describe())
The supplier and category arrive as numeric codes here for brevity. In a real model they would be one hot encoded, because a code of 7 is not "more" than a code of 3. The clip keeps fills inside the range of real cost ratios. And the flag is taken before the fill, because afterwards there is no way to tell.
Gaps in time series: carry forward, interpolate, or use the season
Time series have their own toolkit, because neighbouring values carry information:
- Last observation carried forward (LOCF): repeat the last known value. Right for values that only change when something happens, such as a price or a stock level recorded on change. Dubious for flows such as daily orders, and van Buuren notes it can bias results even under MCAR8.
- Linear interpolation: draw a straight line between the values either side of the gap. pandas offers it through
Series.interpolate, including atimemethod that respects uneven gaps between dates13. - Seasonal reference: take the same period last year and scale it by how this year compares with last year in the weeks you do have. This uses the one thing interpolation cannot know: that the gap may contain a peak.
Linear interpolation between the known points and (see Foundations: ratios and rates) is
where is the filled value at time , and and are the observed values at the last time before the gap, , and the first time after it, .
The seasonal fill (see Foundations: seasonality) is
where is the value in the same week last year, the set of weeks observed in both years, and the fraction is this year's level relative to last year's.
Example: the two weeks the 3PL file never arrived
In January, the 3PL warehouse changed its file server and the returns files for weeks 5 and 6 never reached Shannonside. The weekly returns chart showed two zeros. Here is what each method makes of the gap, with the truth that arrived when the warehouse resent the files a month later:
| Week | 4 | 5 | 6 | 7 |
|---|---|---|---|---|
| Truth (resent later) | 44 | 52 | 58 | 47 |
| Gap as zero | 44 | 0 | 0 | 47 |
| Carried forward | 44 | 44 | 44 | 47 |
| Linear interpolation | 44 | 45 | 46 | 47 |
| Seasonal reference | 44 | 51.5 | 57.8 | 47 |
The interpolation looks grand on a chart. Worked through: , , , , so week 5 is and week 6 is .
The seasonal fill, worked. Last year, weeks 5 and 6 had 49 and 55 returns. In the ten weeks observed in both years, this year had 415 returns and last year 395:
So this year runs at times last year's level. Week 5: . Week 6: .
Over the twelve weeks the shop sent about 5,484 orders. The return rate each method implies: truth 525 returns, 9.57%. Zero fill 415, 7.57%. Carried forward 503, 9.17%. Linear 506, 9.23%. Seasonal 524.3, 9.56%. The smooth methods missed the post Christmas peak because they cannot know it exists. The seasonal fill knew, because last year had one.
In pandas, with the flag kept:
# Python 3, pandas: fill short gaps in a weekly series and flag them
import pandas as pd
weekly = pd.read_parquet("clean/returns_weekly.parquet").set_index("week_start")["returns"]
# weeks without a file are NaN here, never 0: a missing file is not a week without returns
is_gap = weekly.isna()
filled_linear = weekly.interpolate(method="time", limit=2, limit_area="inside")
filled_ffill = weekly.ffill(limit=1)
result = pd.DataFrame({
"returns_raw": weekly,
"returns_filled": filled_linear,
"is_imputed": is_gap & filled_linear.notna(),
})
limit=2 stops the fill after two consecutive gaps, so a month long outage stays visible instead of turning into a confident straight line, and limit_area="inside" only fills gaps with real values on both sides13. In forecasting, the filled weeks feed the model but are left out when you measure forecast accuracy, which forecasting in eCommerce covers in depth.
Multiple imputation: putting the uncertainty back
Every single fill, however clever, has the same flaw: it treats a guess as a measurement. Rubin's answer, set out in his 1987 book, is multiple imputation14. Instead of filling each gap once, you fill it times, each time drawing a plausible value that includes the model's uncertainty. You run your analysis on each of the completed datasets, then combine the results with a fixed set of formulas known as Rubin's rules15.
The spread between the results is the point. Where the data pin the answer down, the results agree. Where the gaps matter, they disagree, and that disagreement enters the final standard error.
Rubin's rules, for one estimate such as a mean, a rate or a regression coefficient (see Foundations: confidence intervals):
where is the number of imputed datasets, the estimate from dataset , its squared standard error, the pooled estimate, the average within imputation variance, the between imputation variance, and the total variance, whose square root is the pooled standard error. The extra term accounts for using a finite number of imputations15. The share of the total variance that comes from the gaps, , is the fraction of missing information.
How many imputations? The classic advice was 3 to 5. The current rule of thumb, which van Buuren reports has become the de facto standard, is to set close to the percentage of incomplete cases, so 20 or more is common, and to use 5 while you are still building the imputation model16.
Example: pooling five margin estimates
Callum wants the margin rate as an input to a pricing model, not just for one report, so he treats last month as a sample of how the shop trades. He imputes the missing cost ratios five times with predictive mean matching and computes the margin on each completed dataset. Each estimate has a standard error of 0.30 percentage points from the sampling of order lines, so each .
The five estimates, in %: 42.0, 42.3, 42.1, 42.4, 42.2.
Pooled estimate:
So , in %. The deviations from it are minus 0.2, 0.1, minus 0.1, 0.2 and 0, whose squares add to 0.10:
So the between variance is . Within variance . Total:
So , and the pooled standard error is points, against 0.30 from any single imputation. The fraction of missing information is . A 95% interval of roughly 1.96 standard errors either side gives 42.2% plus or minus 0.68, so 41.5% to 42.9%. (Rubin's rules use a t distribution with adjusted degrees of freedom, which libraries handle for you. With this much data the difference from 1.96 is small.) The true margin, 41.8%, sits inside. A single imputation would have reported 42.2% plus or minus 0.59, an interval that is too sure of itself.
In Python, scikit-learn's IterativeImputer produces multiple imputations when you set sample_posterior=True and run it with different random seeds12. The pooling is a few lines:
# Python 3: multiple imputation of cost ratios and Rubin's rules for the margin
import numpy as np
import pandas as pd
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.impute import IterativeImputer
def margin_and_variance(lines: pd.DataFrame) -> tuple[float, float]:
cost = lines["revenue_ex_vat"] * lines["cost_ratio"]
margin = 1 - cost.sum() / lines["revenue_ex_vat"].sum()
# within imputation variance from a bootstrap over order lines would go here;
# a fixed value keeps the example short
return margin, 0.0030 ** 2
def pool(estimates: list[float], variances: list[float]) -> dict:
m = len(estimates)
q_bar = float(np.mean(estimates))
u_bar = float(np.mean(variances))
b = float(np.var(estimates, ddof=1))
t = u_bar + (1 + 1 / m) * b
return {"estimate": q_bar, "se": t ** 0.5, "fmi": (1 + 1 / m) * b / t}
lines = pd.read_parquet("clean/order_lines_with_features.parquet")
features = ["cost_ratio", "price_ex_vat", "weight_kg", "supplier_code", "category_code"]
estimates, variances = [], []
for seed in range(20):
imputer = IterativeImputer(sample_posterior=True, random_state=seed, max_iter=10)
completed = lines.copy()
completed[features] = imputer.fit_transform(lines[features])
completed["cost_ratio"] = completed["cost_ratio"].clip(0.05, 0.95)
q, u = margin_and_variance(completed)
estimates.append(q)
variances.append(u)
print(pool(estimates, variances))
For regression models, statsmodels has a MICE class that runs the imputations and pools the fitted model for you (MICE stands for multivariate imputation by chained equations)17. Van Buuren's R package mice is the reference implementation, and his book is the best free guide to all of this.
One warning from the experienced end: do not average the datasets into one and analyse that. It throws away exactly the between imputation spread that multiple imputation exists to keep. Analyse each, then pool the results.
Flags: the column that keeps you honest
Whatever method you use, keep a record of which values were filled. One boolean column per filled field (cost_ratio_imputed, returns_is_imputed), or one text column naming the source (supplier, category_median_ratio, unknown). It costs almost nothing and buys three things: reports can show how much of a number rests on estimates, you can rerun any analysis on observed values only, and a model can learn from the fact that something was missing.
That last use needs care. In prediction, a missing indicator is often a strong feature, and scikit-learn imputers take an add_indicator=True parameter that appends one column per feature with gaps12. In inference, where you want to know how much one thing affects another, the old "indicator method" (fill with zero and add the indicator to a regression) can give badly biased estimates even under MCAR, outside a few narrow situations such as randomised trials18. So: indicators are welcome as predictors, and suspect as a fix for estimating effects.
Example: the missing phone that predicts returns
Callum builds a model to flag orders likely to be returned, so the customer service team can call ahead. Among the 475 orders without a usable phone number, the return rate was 14.1%, against 9% overall (invented figures for the example). The indicator phone_missing goes into the model as a feature, and it helps the predictions. What Callum does not do is tell Niamh that "a missing phone number causes returns". The missingness is a symptom: it is twice as common on mobile, and mobile buyers may simply return more. For prediction that does not matter. For a decision about the checkout form, it matters a great deal.
Building it into the pipeline
Imputation in a production pipeline follows the same rules as every other cleaning step in this series: the raw value is never overwritten, every rule is written down with a version, and every filled value can be traced back.
In practice, at Shannonside:
- Raw layer: exactly what arrived, including the NULLs, empty strings and fake zeros.
- Staging layer: all forms of empty turned into one NULL, structural gaps given their own state, but nothing filled.
- Clean layer: filled columns next to the raw ones, with a source column and the rule version.
- Reports and models: choose explicitly which column to use, and show the imputed share.
A later chapter in this series covers the layers themselves in depth. Here is how Callum's cost price fill looks as a dbt Core model and its tests:
-- models/clean/clean_variant_costs.sql (dbt Core, PostgreSQL adapter)
{{ config(materialized='table') }}
select
variant_id,
cost_price_raw,
cost_price_filled,
cost_price_source,
'cost_fill_v2' as cost_fill_rule_version -- matches the entry in the rule register
from {{ ref('int_variant_cost_fill') }}
# models/clean/clean_variant_costs.yml (dbt Core)
models:
- name: clean_variant_costs
columns:
- name: cost_price_source
data_tests:
- accepted_values:
arguments:
values: ['supplier', 'category_median_ratio', 'unknown']
- name: cost_price_raw
data_tests:
- not_null:
config:
where: "cost_price_source = 'supplier'"
- name: cost_price_filled
data_tests:
- not_null:
config:
severity: error
warn_if: ">50"
error_if: ">150"
The first test makes sure no new, undocumented source sneaks in. The second makes sure every row labelled as a supplier cost really has a raw value, using the where config to filter the tested rows19. The third is the alarm, counting the rows that stayed unknown: a few unknown costs produce a warning, but more than 150 stop the build, because at that point the margin report is mostly guesswork and someone needs to chase the supplier. dbt checks error_if first, then warn_if20.
The Python fill functions get unit tests like any other code, written first:
# tests/test_fill_weekly.py (pytest)
import pandas as pd
from pipeline.fill import fill_weekly_gaps
def test_fills_short_gap_and_flags_it():
s = pd.Series([44.0, None, None, 47.0],
index=pd.date_range("2026-01-26", periods=4, freq="W-MON"))
out = fill_weekly_gaps(s, max_gap=2)
assert out["returns_filled"].tolist() == [44.0, 45.0, 46.0, 47.0]
assert out["is_imputed"].tolist() == [False, True, True, False]
assert out["returns_raw"].isna().sum() == 2 # the raw values are untouched
def test_leaves_long_gap_visible():
s = pd.Series([44.0, None, None, None, 47.0],
index=pd.date_range("2026-01-26", periods=5, freq="W-MON"))
out = fill_weekly_gaps(s, max_gap=2)
assert out["returns_filled"].isna().sum() == 3
The second test pins the rule that a long outage must stay visible. Test driven development explained shows why writing that test before the function changes how you design it.
One trap catches experienced engineers in machine learning work: fit the imputer on the training data only. If the mean or the model that fills the gaps has seen the test data, information leaks from the test set into training, and the model looks better than it will be in production. Put the imputer inside a scikit-learn Pipeline, which fits every step on the training folds only12.
Reporting versus modelling: different rules for the same gap
The same missing value deserves different treatment depending on who reads the result. This is the table Callum and Niamh agreed for Shannonside:
| Use | Rule for missing values | Why |
|---|---|---|
| Finance, VAT, statutory accounts | Never impute an amount. Report unknowns as unknown and chase the source | These numbers must be facts, and auditors ask where each one came from |
| Management dashboard | Impute where it is defensible, show the share imputed on the tile | A decision needs a best estimate, and a reader needs to see how firm it is |
| Operational lists (who to call, what to ship) | Never impute. A missing phone means no call, not a guessed number | Acting on a guess about a real person causes real harm |
| Forecasting | Fill short gaps in history with flags, leave them out of accuracy checks | Models need continuous history, but must not be graded on their own guesses |
| Machine learning features | Impute inside the pipeline, add indicators | Predictions benefit, and leakage is avoided |
| Estimating effects (pricing, experiments) | Multiple imputation, with a complete case analysis alongside | Only multiple imputation carries the uncertainty into the standard errors |
How to report numbers that rest on filled values
A filled value is fine. A filled value nobody knows about is not. Jonathan Sterne and seven colleagues published reporting guidance in the BMJ for medical research that transfers almost word for word to a business report: report how many values are missing for each variable, give the reasons where you can, compare the complete and incomplete groups, state the method and its assumption (for example MAR), say how many imputations you made, and show the complete case result alongside for comparison21. For a dashboard tile, compress that into one line and a link.
For anything that might be MNAR, add a sensitivity analysis: repeat the calculation under a few plausible "what if the missing values were different" scenarios and show the range. Van Buuren calls the simplest form a delta adjustment: shift the imputed values by a fixed amount and see how far the result moves22.
For the margin example, the imputed cost of the lines without a cost price is
where is the revenue of the lines without a cost price, the imputed cost ratio and the assumed error in that ratio. The fraction works like any rate (see Foundations: ratios and rates).
Example: the margin line Niamh actually sees
With euro and , Callum computes three scenarios. If the new supplier is 5 points less expensive than the category (), the cost is euro and the margin:
A margin of . If the supplier is 5 points dearer (), the cost is euro:
A margin of . And at 10 points dearer (), the cost is euro:
A margin of . The tile on Niamh's dashboard now reads: "Gross margin 42.2%. 9.3% of revenue uses estimated cost prices (new lighting supplier, invoices pending). Plausible range 41.2% to 42.6%." That is one sentence longer than "47.9%", and it is the difference between a decision and a mistake. When the invoices arrive, the figure is restated to 41.8%, and the change is logged. A later chapter in this series covers restating reported numbers without losing trust.
Missing personal data and the law
Missing values about people deserve extra care, because filling them creates information about a real person. Under the GDPR, personal data must be "accurate and, where necessary, kept up to date", and inaccurate data must be erased or rectified without delay (Article 5(1)(d))23. The Data Protection Commission's summary of the principles adds a point that fits imputation exactly: controllers "should accurately record information they collect or receive and the source of that information"24.
In practice that gives three rules. Never write an imputed value back into the customer record in the shop, where staff or systems would treat it as something the customer told you. Keep imputed values about people in the analytics layer, flagged as estimates, used only for aggregate analysis. And never fill a contact detail: a guessed phone number or email reaches a real stranger. This is general information about the law, not legal advice for your situation.
Example: the 475 phone numbers
The shop's courier needs a phone number for some deliveries. Callum's pipeline never fills phone. Instead, the staging layer turns all five forms of empty into NULL, a phone_status column says missing or invalid, and the customer service queue gets a daily list of upcoming deliveries without a usable number, so someone can email the customer and ask. The 2% gap shrinks at the source, by asking the person, which is the only fill that is both accurate and lawful.
A decision path for every gap
Put together, this is the path Callum follows for every missing value:
The order matters. The fastest and most accurate fix is almost always the source, and the most expensive mistake is filling a value that should never have been filled.
Conclusion
Missing data is not a technical nuisance to be cleared before the real work. It is information about how your data came to be, and every way of handling it makes an assumption about that process. Find every form of empty first: NULLs, empty strings, placeholders, sentinel dates, zero defaults such as the Solidus weight, and the rows that are not there at all. Separate "not applicable" and "not yet known" from truly unknown. Ask why values are missing, knowing that data can rule out MCAR but can never prove MAR. Prefer the source to any method. Never use a fake default. Use deletion only for small, plausibly random gaps, fill within the groups or with a model that explains the gap, use multiple imputation when you need honest standard errors, and use seasonal references for time series with peaks. Keep the raw value, flag every fill, test the rules, and report the imputed share and a plausible range next to the number. Do that, and the Monday morning numbers will be less exciting and a great deal more useful.
