Sub topic 11
How Missing Values Flow Into New Columns
This chapter assumes you can build a DataFrame, select columns by name, and write simple vectorized expressions such as df["a"] * df["b"]. You should also know that pandas marks a missing number as NaN (not a number). Here you will learn what happens to those gaps when you derive new columns, where they silently change your results, and how to handle them on purpose.
The default rule: arithmetic propagates NaN
A missing value means "unknown." Any arithmetic with an unknown input gives an unknown result. pandas follows this rule element by element.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp", "desk"],
"price": [1.5, 12.0, None, 30.0],
"qty": [10, 3, 2, None],
})
df["total"] = df["price"] * df["qty"]
print(df)
# total: 15.0, 36.0, NaN, NaNThe lamp row has no price and the desk row has no quantity, so both totals are NaN. This is usually what you want, because a made-up total would be worse than a visible gap.
Notice that qty is stored as floats (10.0, 3.0). A plain integer column cannot hold NaN, so pandas converts the whole column to float64 when a missing value appears. The "Missing integers" section below covers the fix.
Where the rule changes
Not every operation propagates NaN. The table summarizes the behaviors that most often surprise people.
| Operation | Result for a missing input |
|---|---|
| `a + b`, `a * b` | `NaN` |
| `a > 5`, `a == 5` | `False` |
| `a == np.nan` | `False`, even for missing values |
| `np.where`, `np.select` | The "else" or default branch |
| `.str` methods | `NaN` |
| `.dt` accessor | `NaT` (not a time) for the part you extract, shown as `NaN` |
| `Series.map(dict)` for an unlisted key | `NaN` |
| `pd.to_numeric(..., errors="coerce")` | `NaN` for unparseable text |
| `pd.cut`, `pd.qcut` | `NaN` |
| `df[[...]].sum(axis=1)` | Skips missing values by default |
The two rows that deserve the most attention are comparisons and row-wise sums. They are the cases where a gap turns into a plausible but wrong value.
Comparisons and conditional columns
A comparison against a missing value returns False. That is a problem when you feed the comparison into np.where or np.select, because False sends the row to the fallback.
df["tier"] = np.select(
[df["price"] < 5, df["price"] < 20],
["low", "mid"],
default="high",
)
print(df[["item", "price", "tier"]])
# lamp has no price, but it is labeled "high"Neither condition is true for lamp, so it receives the default, "high". That label is wrong. The fix is to test for missing values first. np.select uses the first matching condition, so order matters.
df["tier"] = np.select(
[df["price"].isna(), df["price"] < 5, df["price"] < 20],
["unknown", "low", "mid"],
default="high",
)Now lamp is "unknown", and "high" only appears for prices of 20 or more. Always use isna() or notna() to test for missing values. The expression df["price"] == np.nan is always False for every row, because NaN is not equal to anything, including itself.
Missing values from other steps
Gaps also appear in new columns without any NaN in the arithmetic.
Recoding and parsing
map returns NaN for any value that is not a key in the dictionary. to_numeric with errors="coerce" turns text it cannot parse into NaN. In both cases the new column has gaps that the source column did not.
codes = df["item"].map({"pen": "P", "book": "B"})
nums = pd.to_numeric(pd.Series(["1", "2", "x"]), errors="coerce")
print(codes.isna().sum()) # 2 (lamp and desk)
print(nums.isna().sum()) # 1 (the "x")Counting the new gaps right after the conversion is a cheap check that catches typos in a mapping or unexpected text in a number column.
Index alignment
When you assign a Series to a column, pandas matches rows by index label, not by position. Labels that do not match become NaN.
bonus = pd.Series([5, 7], index=[0, 3])
df["bonus"] = bonus
print(df["bonus"].tolist())
# [5.0, nan, nan, 7.0]This often happens after you filter or sort one object and then assign it back to another. If you really want positional assignment, pass bonus.to_numpy(), and make sure the length matches.
Group keys
groupby(...).transform(...) drops rows whose group key is missing by default, so those rows get NaN in the new column. Pass dropna=False to groupby if you want missing keys treated as a group of their own.
Choosing a strategy
You have three options for each gap: leave it, fill it, or flag it. Choose based on what the missing value means.
Leave it
If the value is truly unknown, NaN is honest. Later mean() and sum() calls skip missing values by default, so the gap does not damage summaries.
Fill it
fillna replaces gaps with a value you supply. The value can be a constant or a statistic.
df["price_missing"] = df["price"].isna()
df["price_filled"] = df["price"].fillna(df["price"].median())
df["qty_filled"] = df["qty"].fillna(0)
df["total_filled"] = df["price_filled"] * df["qty_filled"]The median of the known prices (1.5, 12.0, 30.0) is 12.0, so lamp gets a price of 12.0. This choice has consequences. Filling qty with 0 says "none were sold," which may not be true. Fill only when you can defend the value, and record the decision.
The price_missing column is a flag. It keeps the information that the filled value was a guess, so you can exclude those rows later.
For recoding, chain the fill onto the result: df["item"].map(mapping).fillna("other").
Row-wise sums skip gaps
Aggregating across columns treats NaN differently from +.
parts = df[["price", "qty"]]
df["row_sum"] = parts.sum(axis=1) # skips NaN: lamp gets 2.0
df["row_sum_strict"] = parts.sum(axis=1, skipna=False) # lamp gets NaNprice + qty gives NaN for lamp, but sum(axis=1) gives 2.0. The two look like the same calculation, and they are not. Use skipna=False when a partial total would mislead. You can also pass min_count=2 to require at least two valid values.
Missing integers
Because plain integer columns cannot hold NaN, a single gap turns the column into floats. pandas offers nullable integer types that keep whole numbers and mark gaps with pd.NA.
qty = pd.Series([10, 3, None]).astype("Int64")
print(qty * 2)
# 20, 6, <NA> with dtype Int64Note the capital I in Int64. The lowercase int64 is the plain NumPy type and will raise an error if the column contains missing values. Nullable types propagate pd.NA in arithmetic much like NaN, but they keep the integer meaning of the column.
Exercise
A DataFrame has a float column score with some NaN values. You write df["result"] = np.where(df["score"] >= 50, "pass", "fail"). What result do rows with a missing score get, and how do you change the code so they get "no score"?
Show answer
They get "fail", because NaN >= 50 is False and np.where sends False rows to the else value. Use np.select([df["score"].isna(), df["score"] >= 50], ["no score", "pass"], default="fail"). The isna() condition comes first so missing scores match it before any comparison.
Exercise
Two columns a and b have NaN in the same row. df["a"] + df["b"] gives NaN for that row, but df[["a", "b"]].sum(axis=1) gives 0.0. Why, and how do you make the sum return NaN?
Show answer
The + operator propagates missing values, while sum skips them by default, so a row with only missing values sums to 0.0. Call df[["a", "b"]].sum(axis=1, skipna=False) to get NaN, or use min_count=1 to require at least one valid value.