Sub topic 11
How missing values flow into new columns
This chapter assumes you can build a DataFrame, select a column by name, and use vectorized arithmetic and np.select. pandas marks missing numbers as NaN (not a number). A derived column inherits that gap in some operations and hides it in others.
Arithmetic propagates NaN
An arithmetic operation with a missing value returns a missing value. The gap travels into the new column on its own.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, None, 30.0],
"qty": [10, 3, 2],
})
df["total"] = df["price"] * df["qty"]
print(df)The book row has NaN in total. The price column is float64 because plain integers cannot hold NaN.
Comparisons turn NaN into False
A comparison with NaN does not return NaN. It returns False, so a missing price looks like an ordinary row that failed the test.
print(df["price"] > 20)This prints False, False, True. The missing price is not flagged.
df["tier_wrong"] = np.where(df["price"] > 20, "high", "low")This labels the unknown price low. Test for missing values first, because np.select uses the first matching condition.
df["tier"] = np.select(
[df["price"].isna(), df["price"] > 20],
["unknown", "high"],
default="low",
)Other tools that create missing values
Some operations create gaps without any NaN in the input.
Series.mapwith a dictionary returnsNaNfor keys the dictionary lacks.pd.to_numeric(..., errors="coerce")turns unparseable strings intoNaN.pd.to_datetime(..., errors="coerce")turns bad dates intoNaT, the datetime version ofNaN.pd.cutgivesNaNto values outside every bin.
Aggregations skip, operators do not
Reductions such as sum and mean skip missing values by default. The + operator does not.
scores = pd.DataFrame({"a": [1, 2, None], "b": [4, None, None]})
scores["plus"] = scores["a"] + scores["b"]
scores["sum_skipna"] = scores[["a", "b"]].sum(axis=1)
scores["sum_strict"] = scores[["a", "b"]].sum(axis=1, skipna=False)
print(scores)| Row | `a + b` | `sum(axis=1)` | `sum(axis=1, skipna=False)` |
|---|---|---|---|
| 0 | 5.0 | 5.0 | 5.0 |
| 1 | NaN | 2.0 | NaN |
| 2 | NaN | 0.0 | NaN |
Row 2 shows a trap. sum returns 0.0 when every value is missing, which looks like real data. Pass min_count=1 to get NaN there instead.
Detecting and filling gaps
Use isna() to flag missing values and fillna() to replace them. Fill only when you can justify the replacement value.
df["price_missing"] = df["price"].isna()
df["price_filled"] = df["price"].fillna(df["price"].median())The median of 1.5 and 30.0 is 15.75, so the book row gets that price. Keep the price_missing flag so you can still tell filled rows from real ones.
Exercise
A DataFrame has a column "age" with values [25, NaN, 70]. You run np.where(df["age"] >= 65, "senior", "adult"). What label does the NaN row get, and how would you label it "unknown" instead?
Show answer
It gets "adult", because NaN >= 65 is False. Use np.select with the missing-value test first: np.select([df["age"].isna(), df["age"] >= 65], ["unknown", "senior"], default="adult").