Quick answer
Leave values missing when they are genuinely unknown. Drop records only from analyses that require the missing fields, and report what was excluded. Fill values when a documented rule establishes their meaning, or when an explicitly labeled estimation method fits your purpose. Deletion can introduce bias; filling does not recover the unknown truth. (bmj.com)
The useful question is not “How do I remove every blank?” It is “What does this blank mean, and what will my analysis assume about it?”
This tutorial uses a small, synthetic customer-orders dataset to show how different choices change the same summary. You need basic Python knowledge and pandas. The APIs were checked against the official pandas 3.0.6 documentation; record your installed version with print(pd.__version__). (pandas.pydata.org)
1. Start with the question and the meaning of each blank
Write down the intended calculation before changing the data. For our example:
What is the average recorded order amount, and how much amount data is missing?
Then distinguish the reasons a field might be empty:
| Meaning | Suggested treatment |
|---|---|
| Value exists but was not captured | Preserve as unknown; investigate recovery |
| Field does not apply | Preserve that reason separately |
| Value is explicitly known to be zero | Record zero under the documented rule |
| Value is being estimated | Keep an imputed version and identify replacements |
These are different situations, even if an export represents all of them as empty cells. Data-preparation guidance recommends distinguishing missing-data reasons and identifying imputed values rather than silently overwriting them. (icpsr.umich.edu)
For example, an absent delivery date could mean “not dispatched,” “digital purchase,” or “export failed.” Ask which interpretation the source system supports.
Do not assume an unknown order amount is zero. In this example, zero would assert that the order had no monetary value. A missing value asserts that we do not know its amount.
Before cleaning, define practical constraints: which fields must exist, whether negative amounts are legitimate, and what categories or rating values are permitted.
2. Build the example with explicit data types
Each row below represents one order, not one customer. Customer identifiers can repeat. Amounts are hypothetical currency units for completed purchases, excluding refunds. Ratings use a synthetic 1–5 scale.
import pandas as pd
orders = pd.DataFrame({
"order_id": range(1, 9),
"customer_id": ["C1", "C2", "C1", "C3",
"C4", "C5", "C6", "C7"],
"channel": ["Web", "Web", "Web", "Web",
"Store", "Store", "Store", "Store"],
"order_amount": [20, 40, 60, 80, 100, 120, None, None],
"rating": [5, None, 4, 3, 5, 4, 2, None],
}).astype({
"order_id": "Int64",
"customer_id": "string",
"channel": "string",
"order_amount": "Float64",
"rating": "Int64",
})
print(pd.__version__)
print(orders.dtypes)
The capitalized Int64 and Float64 names select pandas’ nullable numeric types. They allow numeric values and missing values in the same column. Missing-value representations depend on type: you may encounter pd.NA, floating-point NaN, or NaT for dates and times. (pandas.pydata.org)
Use isna() to detect missingness rather than comparing values with NaN or pd.NA. An actual empty string is not automatically considered missing by isna(). Neither is infinity. (pandas.pydata.org)
For imported data, inspect the source’s conventions. Replace a token such as "Unknown" only when the field documentation says it represents missingness. Do not apply a blanket replacement to every column.
3. Profile missingness before choosing a treatment
Start with counts and percentages:
profile = pd.DataFrame({
"missing_count": orders.isna().sum(),
"missing_pct": orders.isna().mean().mul(100),
})
print(profile)
Expected values:
| Column | Missing count | Missing percentage |
|---|---|---|
| order_id | 0 | 0.0 |
| customer_id | 0 | 0.0 |
| channel | 0 | 0.0 |
| order_amount | 2 | 25.0 |
| rating | 2 | 25.0 |
Next, inspect whether missingness is concentrated in a relevant group:
amount_missing_pct = (
orders.assign(amount_missing=orders["order_amount"].isna())
.groupby("channel")["amount_missing"]
.mean()
.mul(100)
)
print(amount_missing_pct)
Expected result:
Store 50.0
Web 0.0
In this toy dataset, all missing amounts belong to store orders. That deserves investigation before presenting a combined average.
Also check combinations of missing fields:
print(orders[["order_amount", "rating"]].isna().value_counts())
This distinguishes orders missing only an amount, only a rating, or both. Keep the original dataset unchanged while investigating; maintain separate analysis versions and identify any imputed values. (icpsr.umich.edu)
Treat this profile as a diagnostic, not a verdict. Eight invented orders cannot establish how a real data-collection process behaves.
4. Understand MCAR, MAR and MNAR without guessing
Statistical guidance distinguishes three missingness mechanisms:
- Missing completely at random (MCAR): missingness is unrelated to observed or unobserved values.
- Missing at random (MAR): after accounting for observed information, missingness does not depend on the missing value itself.
- Missing not at random (MNAR): missingness still depends on the unobserved value after accounting for observed information. (pmc.ncbi.nlm.nih.gov)
Imagine an export randomly omitting amounts regardless of order characteristics: an MCAR scenario. If omission depends only on the recorded channel, that could fit MAR. If larger orders are more likely to have their amounts omitted even within each channel, MNAR is a concern.
These examples are hypothetical explanations—not conclusions from the dataset.
Observed differences can provide evidence against MCAR. However, observed data alone cannot establish MAR rather than MNAR. Investigate collection rules, export behavior and missing-value reasons. (pmc.ncbi.nlm.nih.gov)
In particular, “MAR” does not mean that blanks appear randomly across the spreadsheet. Missingness can have a visible pattern associated with recorded information.

5. Choose between targeted deletion, filling and preservation
Drop only what the calculation requires.
If an amount-based calculation requires known amounts, create a specific subset:
amount_complete = orders.dropna(subset=["order_amount"])
This keeps six orders. In contrast:
complete_everywhere = orders.dropna()
keeps only five, because it also excludes the order with a missing rating but a known amount. By default, dropna() removes rows containing any missing value; subset restricts which columns matter. (pandas.pydata.org)
Deletion may be acceptable for describing the retained records, but do not automatically generalize that description to every order. Complete-case analysis can lose information and produce biased estimates. (bmj.com)
Fill only under an explicit rule or assumption.
fillna() replaces missing entries with specified values. It does not determine whether those replacements are statistically defensible. (pandas.pydata.org)
For a deliberately labeled median-fill scenario:
median_scenario = orders.copy()
median_scenario["amount_imputed"] = (
median_scenario["order_amount"].isna()
)
median_scenario["order_amount"] = (
median_scenario["order_amount"]
.fillna(orders["order_amount"].median())
)
The replacement is 70, calculated from the six observed amounts. This is an assumption, not a recovered transaction value.
Single imputation does not account for the full uncertainty about missing values; treating replacements as observed data can underestimate standard errors. (pmc.ncbi.nlm.nih.gov)
Leave unknowns missing when that is the honest representation.
You can retain every order while reporting the mean of available amounts. pandas’ mean() excludes missing values by default. State its denominator clearly. (pandas.pydata.org)
Avoid forward-filling unrelated orders. Forward fill carries a preceding value into a gap; that behavior supplies no business reason why the next order should have the same amount. (pandas.pydata.org)
6. Compare treatments using the same summary
Run this after the preceding code:
zero_scenario = orders.copy()
zero_scenario["order_amount"] = (
zero_scenario["order_amount"].fillna(0)
)
versions = {
"Leave missing": orders,
"Drop missing amounts": amount_complete,
"Drop any missing field": complete_everywhere,
"Fill amounts with zero": zero_scenario,
"Fill amounts with median": median_scenario,
}
comparison = pd.DataFrame([
{
"treatment": name,
"rows": len(frame),
"amounts_available": frame["order_amount"].count(),
"amount_sum": frame["order_amount"].sum(min_count=1),
"amount_mean": frame["order_amount"].mean(),
}
for name, frame in versions.items()
]).set_index("treatment")
print(comparison.round(2))
Expected results:
| Treatment | Rows | Amounts available* | Amount sum | Amount mean |
|---|---|---|---|---|
| Leave missing | 8 | 6 | 420.00 | 70.00 |
| Drop missing amounts | 6 | 6 | 420.00 | 70.00 |
| Drop any missing field | 5 | 5 | 380.00 | 76.00 |
| Fill amounts with zero | 8 | 8 | 420.00 | 52.50 |
| Fill amounts with median | 8 | 8 | 560.00 | 70.00 |
*“Available” means non-missing in that analysis version; filled values are not newly observed amounts.
The original six amounts total 420:
- Available-case mean:
420 / 6 = 70. - Zero-filled mean:
420 / 8 = 52.5. - Median-filled mean:
(420 + 70 + 70) / 8 = 70.
The unchanged median-filled mean does not validate the replacement. It conceals two estimates inside an apparently complete column.
Likewise, the original 420 is an observed subtotal, not a verified total for all eight orders.
sum(min_count=1) avoids reporting zero when every amount is missing. It still permits partial sums; it does not require every order to have an amount. For a deliberately strict total, use sum(skipna=False), which returns a missing result when any amount is missing. (pandas.pydata.org)
7. Validate the result and document the decision
For this example’s stated rules, check identifiers, known amounts and ratings:
assert orders["order_id"].notna().all()
assert orders["order_id"].is_unique
assert orders["order_amount"].dropna().ge(0).all()
assert orders["rating"].dropna().between(1, 5).all()
assert len(median_scenario) == len(orders)
assert median_scenario["amount_imputed"].sum() == 2
These checks implement the toy dataset’s rules. Adjust them for real data: refunds, for instance, may require different amount constraints.
Before publishing, ask:
- Did an unrelated optional field cause records to disappear?
- Did a replacement violate a field’s meaning or permitted range?
- Are observed and imputed values distinguishable?
- Is the denominator stated for every mean or percentage?
- Does the conclusion change under plausible alternative assumptions?
A clear description of our example would be:
“Six of eight orders have recorded amounts. Their observed subtotal is 420 currency units and their mean is 70. Both missing amounts occur among store orders. The total and mean across all eight orders remain unknown.”
Document the source, analysis date, pandas version, missingness profile, exclusions, replacement rule and unresolved reasons for missingness. Retaining original variables or imputation flags makes replacements identifiable. (icpsr.umich.edu)
For formal inference, simple filling may be inadequate. Multiple imputation creates several plausible completed datasets and combines their analysis results to account for missing-value uncertainty. It requires appropriate modeling and assumptions—not merely repeated calls to fillna(). (bmj.com)
The goal is a defensible answer, not a dataset with no blanks.
