Chapter 5 — Data Cleaning: “Archive Hygiene”

Missing values: why you can't just fill them in

18 min

Three archives with the same gaps

The year is 2184. You're at Vault-9 station, looking at Kotomarket's black box. The cat-supply marketplace is gone, but its data survived. Its delivery cities were Furrville, Catford, Meowfield, and Tailford.

QUERY: “Three exports. Exactly 20% of amount is missing in each one. Same number. Three different stories. I checked. Repeatedly.”

A missingness mechanism describes how missing values relate to the rest of the data. If the probability that a value is missing is unrelated to both the value itself and the order's other attributes, the missingness is random. If there is a relationship, the missingness is systematic.

ArchiveMechanismWhat happens if you drop the rows
A — randomrandom synchronization failures prevented some amount values from being recorded; the failures are unrelated to either the amount or the order's attributeson average, the structure of the data stays the same, but you have fewer observations
B — systematic by attributethe gateway lost amount for payments made with foreign cardsorders using that payment method disappear, so the metric now describes only the “domestic” market
C — systematic by valuethe field overflowed for amounts above $1000.00you lose the top of the distribution and understate both revenue and average order value (AOV)

The missing rate is 20% in all three archives, but the consequences differ. Start by asking why the values are missing. Decide what to do with them only after that. The cause of missingness is a hypothesis that you test against the data, for example by comparing missing-value rates across segments. If one segment has a 70% missing rate and another has 2%, you've found a pattern that supports a systematic-missingness hypothesis. That difference alone still doesn't prove what caused the failure.

How to measure the gap

In pandas, a missing value can appear as NaN, None, or pd.NA; isna() recognizes all three. The result of isna() is a Boolean mask, a sequence of True and False values.

orders['amount'].isna()         # True/False mask
orders['amount'].isna().sum()   # number of missing values
orders['amount'].isna().mean()  # SHARE missing: 0.15 = 15%
orders.isna().sum()             # missing values in every column at once

Here's how .mean() turns that mask into a proportion. Suppose you have four values and two are missing:

isna()          →  [False, True, False, True]
as numbers      →  [0,     1,    0,     1]
sum()           →  2          # number missing
mean() = 2 / 4  →  0.5        # share missing = 50%

In arithmetic, False becomes 0 and True becomes 1. The sum of the mask therefore tells you how many rows satisfy the condition, while the mean tells you what share of rows satisfy it.

The same technique works beyond isna(): (orders['amount'] > 50.00).mean() calculates the share of rows where the condition is true. But NaN > 50.00 evaluates to False, so rows with no amount still count in the denominator, as if you knew the order was not expensive. If you want the share only among orders with a known amount, exclude the missing values from the denominator first.

Common mistake. String values such as '—', 'no data', and the empty string '' do not count as missing values in pandas by themselves: isna() returns False for them. These disguised missing values need a separate check; we'll cover that in the lesson on data types.

L., entry No. 12: “A third of November orders have no amount. The gateway kept crashing, but the orders were still recorded. The November revenue report is fiction. Horror fiction.”

A cadet studies a holographic capsule registry where two slots glow empty with amber question marks; a robot cat reaches a paw into one of the gaps, and the beam passes straight through.
Five orders, two with no amount.
NaN changes the denominatoramount2000NaN1500NaN2500what pandas doessum = 6000count = 3NaN are not countedmean = 2000if NaN were zerossum = 6000count = 5they would be countedmean = 1200pandas silently dropped NaN from the denominator6000 / 3, not 6000 / 5 — different numbers
The problem with missing values often hides in the denominator: .mean() divides the sum of known values by the number of known values, while after fillna(0) the same sum is divided by the total number of rows.
Five orders, two with no amount. Before you run the cell, predict the average order value (AOV) as is and after fillna(0). Then run it and examine the denominator.
python · pandas

The denominator nobody asked about

Five orders: $10.00, $20.00, $30.00, NaN, NaN. The values included in the calculation still add up to $60.00 in both cases. Only the denominator changes:

What you didDenominatorAOVWhat it means
.mean() as is3$20.00“among orders with a known amount”
fillna(0).mean()5$12.00“if the two orders were free”

One line of code makes AOV fall by 40%. With missing values, the denominator is often where the trouble starts: pandas may silently leave some rows out. By default, .mean(), .sum(), and .median() use skipna=True, so missing values are excluded from the calculation without a separate warning. For the mean, this reduces the denominator. For the sum and median, it changes the set of values included.

QUERY: “The bear in the archive is terrifyingly polite: it'll calculate an average from three orders out of five and never mention it.”

dropna: scalpel versus ax

orders.dropna()                    # drop a row if IT has even one missing value
orders.dropna(subset=['amount'])   # drop only rows with a missing amount

dropna() with no arguments is an ax: a $48.00 order with a known amount gets discarded because its city is missing, even though that column is irrelevant to the revenue calculation. For a more targeted cut, include in subset only the columns required for the metric you're calculating.

fillna: fill attributes, don't invent money

Filling a missing value makes sense when the replacement follows from the system's rules, or when you create an explicit technical category such as unknown to keep the row in the analysis. A filled value should never be presented as a recovered fact. Be especially careful with missing values in an actual business metric: replacing a missing amount with the AOV means inventing money that was never recorded.

ColumnVerified business meaning of NaNWhat to do
discountsystem rules say no discount was appliedfillna(0) is valid
citythe city wasn't recordedfillna('unknown'): keep the row and make the separate segment visible
amountthe amount was lost, but the order existeddon't invent it: exclude it from the calculation, report the number of rows, and mark the result as incomplete
delivered_atthe order hasn't been delivered yetnormal, not dirty data

Pay particular attention to the last row. In event columns, NaN can mean that the event simply hasn't happened yet. Filling that value would create a false fact. Before cleaning a column, check whether an empty value may itself carry meaning.

Audit after the decision

before = len(orders)
clean = orders.dropna(subset=['amount'])
print(before, '->', len(clean), 'rows, dropped', before - len(clean))
print(clean.isna().sum())
print(orders['amount'].mean(), '->', clean['amount'].mean())

In this example, the last comparison gives the same result on both sides: .mean() already skips NaN, and dropna(subset=['amount']) removes those same rows beforehand. The missing values still matter because some orders never contribute to the metric. The first two output lines show how many rows were excluded and whether other columns still contain missing values. In your report, record the number of excluded orders and the share of orders with a known amount. If another treatment of missing values changes AOV, as it did by 40% in the earlier example, state that explicitly.

L., entry No. 13: “The intern filled the missing values with zeros. AOV fell from ~$25.00 to ~$19.00. The board spent an hour discussing a ‘demand catastrophe’ that never happened.”

The column has NaNIs this a valid state?(not delivered → no date)yesnoDo we know the real value?(another source has it)yesnoWould dropping skew data?(NaN are not random)yesnokeep the NaNit is a meaningful "empty"restore itfill from that sourcedo not dropflag it as is_missingdropna(subset=[...])drop by this column only
A decision tree for handling a missing value: first find out why it is missing and what the column means to the business; then choose a tool such as dropna, fillna, or “leave it as is and explain it in the report.”
Practice: write the code
You have 400 orders with missing values in three columns. Measure the missing values and show the denominator: n_missing_amount (number missing in amount), share_missing_amount (their share), denom_skipna (how many values are included in a regular .mean()), denom_zero (how many are included after fillna(0)), plus mean_skipna and mean_zero. Before you run the code, predict which mean will be smaller and explain why.
python · pandas
Practice: write the code
QUERY's hypothesis is: “the gateway lost the amount for foreign cards.” Test it against the data. Calculate the share of missing amount values separately for foreign and local (share_foreign, share_local). Then measure the cost of two cleaning options: how many rows remain after dropna() (rows_dropna_all) and after dropna(subset=['amount']) (rows_dropna_amount). The difference is the number of orders you would discard solely because the city is missing.
python · pandas
Check yourself
The amount column has 20% missing values. An analyst calculated AOV with orders['amount'].mean(). What exactly did they calculate?
Check yourself
The delivered_at column has 35% missing values: some orders have no delivery date. What should you do first?
Interview question

Interview question: “30% of the data needed to calculate a key metric is missing. What do you do?” A strong answer describes a process: 1) investigate possible causes of the missingness by comparing missing-value rates across segments; 2) test how sensitive the result is by recalculating the metric after dropna(subset=['amount']) and under justified fillna scenarios: amounts of $10.00, $20.00, $30.00 and two NaN values produce a mean of $20.00 after dropping the missing values and $12.00 after filling them with zeros; that spread shows how strongly the metric depends on the chosen treatment, but it does not tell you which result is true; 3) choose an approach based on the business meaning of the column and document the choice along with the number of rows removed. A weak answer is “I'll fill them with the mean”: that applies a default treatment before diagnosing the problem.

Key takeaways
  • The same 20% missing rate can represent three different situations. Start by asking why the values are missing; decide how to handle them afterward.
  • Test hypotheses about the cause of missingness with data, for example by comparing isna().mean() across segments.
  • In arithmetic, a mask becomes zeros and ones: sum() gives you the count, while mean() gives you the share.
  • By default, .mean() skips NaN (skipna=True): the mean is calculated only from known values.
  • dropna() is an ax; dropna(subset=[...]) is a scalpel.
  • fillna fills a cell, but it does not recover an unknown value or create money. The meaning of NaN depends on the column: discount can sometimes be replaced with 0, you cannot invent amount, and a missing delivered_at may be perfectly normal.
  • After making a decision, audit the result: compare the row count before and after, check again with isna().sum(), and compare the metric before and after.

Next up: duplicates. A missing value takes a row away; a duplicate adds an extra one.