Build a binary presence matrix with explicit null rules, row order, pattern counts and field-pair support before imputing or dropping records.
Missingness matrices: reveal record-order patterns and co-missing fields
Treat presence as a separate variable
A missingness matrix displays records on one axis and fields on the other, coloring each cell according to whether the field was observed. Its first job is to show structure hidden by overall missing percentages: a whole block lost during one import, one field absent only for a particular cohort, or two fields disappearing together. Define missing before plotting. In this lesson, None and floating-point NaN are missing; zero and an empty string count as observed values unless a separate domain rule says otherwise. That rule must be applied before rendering and recorded with the chart, because changing it can redraw the pattern without changing any source records. An imputed value is not originally observed and should retain a separate provenance flag. Heatmap missing-cell encoding and dashboard provenance support that distinction.
Keep the row order meaningful
A random row order can turn a sustained outage into a scattered texture. Sort records by acquisition time, batch ID or another declared operational sequence, and retain stable unique row identifiers. A secondary sort by missingness pattern can reveal common combinations but destroys chronology; if you use it, label the new order and keep a time-ordered companion view. At large N, drawing every row may produce thousands of subpixel cells. Aggregate into windows, sample with a fixed documented rule, or summarize repeated patterns; never hide rare but consequential failures in an average. Show row count and per-field observed counts beside the matrix. If batches have different schemas, use an explicit not-applicable state rather than treating structurally absent fields as ordinary missing data. Level of detail and time gaps determine how much the reader can see.
Count patterns and pair overlap, not just column rates
Two fields may each be missing in a quarter of records yet fail in completely different rows. A matrix shows the difference; pattern frequencies and pairwise co-missing counts quantify it. The code creates a boolean mask per row, counts each exact pattern, and counts records in which every selected pair is missing. These pair counts are not a correlation coefficient and cannot by themselves explain why values are absent. Show the denominator for every pair: records eligible for both fields. If eligibility changes across rows, restrict the calculation to comparable records or add explicit applicability flags. A pair with no missing records has zero co-missing count, but a field that is always missing cannot be assessed for variation. Pairwise coverage and denominator policy prevent false comparisons.
Do not infer a missing-data mechanism from color blocks
A matrix can expose dependence on observed batches or fields, but it cannot prove that values are missing completely at random, missing at random conditional on observed variables, or missing not at random. The last case depends on unseen values, which the chart cannot display. Avoid turning a visually coherent pattern into an imputation rule without investigating the collection process and validating the downstream model. A form redesign, sensor outage, consent rule or ETL change can all create similar bands. Keep collection timestamps and data-quality events available for annotation; compare raw and post-cleaning views so deletion does not make failure disappear. Use a text table of missing rates, frequent patterns and affected periods for readers who cannot parse a dense matrix. Event annotations and text alternatives keep interpretation bounded.
Worked contract
from collections import Counter
from itertools import combinations
from math import isnan
FIELDS = ("order_total", "delivery_zone", "carrier_id")
def absent(value):
return value is None or (isinstance(value, float) and isnan(value))
def missingness_ledger(records: list[tuple[int, str, dict]]):
seen = set()
matrix = []
pattern_counts = Counter()
pair_counts = Counter()
missing_by_field = Counter()
for period, order_id, values in records:
if (not isinstance(period, int) or not order_id or order_id in seen or
set(values) != set(FIELDS)):
raise ValueError("rows need unique IDs and the declared schema")
seen.add(order_id)
missing = tuple(field for field in FIELDS if absent(values[field]))
pattern_counts[missing] += 1
missing_by_field.update(missing)
pair_counts.update(combinations(missing, 2))
matrix.append((period, order_id, tuple(field in missing for field in FIELDS)))
matrix.sort(key=lambda row: (row[0], row[1]))
return matrix, missing_by_field, pattern_counts, pair_counts
orders = [(50, "order-83", {"order_total": 83.0, "delivery_zone": None,
"carrier_id": None}),
(47, "order-47", {"order_total": 47.0, "delivery_zone": "W",
"carrier_id": "carrier-7"}),
(48, "order-59", {"order_total": float("nan"),
"delivery_zone": "E", "carrier_id": None}),
(51, "order-97", {"order_total": 0.0, "delivery_zone": "",
"carrier_id": "carrier-9"})]
matrix, field_counts, patterns, pairs = missingness_ledger(orders)
assert [row[0] for row in matrix] == [47, 48, 50, 51]
assert field_counts == {"order_total": 1, "delivery_zone": 1, "carrier_id": 2}
assert pairs[("delivery_zone", "carrier_id")] == 1
assert patterns[()] == 2
assert matrix[-1][2] == (False, False, False)Performance and operating cost
For N records and K declared fields, building masks and field counts takes O(NK) time. Counting every missing pair takes O(sum mᵢ²), at most O(NK²), where mᵢ is the number of missing fields in row i; sorting the row ledger adds O(N log N). Matrix storage is O(NK), while pattern and pair counters can reach O(min(N, 2ᴷ) plus K²) entries. The sample has four orders, two fully observed patterns, one missing total, one missing zone and two missing carrier IDs. Only one record loses both zone and carrier. Its final record's zero total and empty zone remain observed under the declared rule; another business rule could mark the empty zone missing, but must be versioned and disclosed.
Common Mistakes
- Conflating zero, empty string, NaN, None and not-applicable without a field contract.
- Sorting rows by missingness and then describing a resulting band as chronological.
- Interpreting co-missing counts as a causal mechanism or a formal correlation measure.
- Removing bad records before charting and presenting the cleaned matrix as raw quality evidence.
Validation drill
Audit 83 ordered import batches with three required fields and one optional field. Publish raw missingness patterns, per-field support and the most common co-missing pair; keep not-applicable separate and annotate any schema or collection change.
