Sub topic 10
Finding and handling missing values
This chapter assumes you can build a Series and a DataFrame, select with loc, and know that arithmetic aligns on the Index. Alignment is the most common source of missing values, so it is a good place to start.
How missing values appear
pandas marks a missing entry as NaN (not a number) in float columns, None in object columns, and NaT in datetime columns. Missing values come from three common sources:
- Empty cells when you read a file.
- Index alignment, when a label exists on only one side of an operation.
- Merges that find no match.
Because NaN is a float, an integer column that gains a missing value is converted to float64. This is why the alignment example in the previous chapter printed 12.0 instead of 12.
Detecting missing values
isna() returns a boolean Series or DataFrame of the same shape. Comparing with == np.nan does not work, because NaN is never equal to anything, including itself. Always use isna() or its opposite, notna().
import pandas as pd
s = pd.Series([1.0, None, 3.0])
print(s.isna().tolist()) # [False, True, False]
print(s.fillna(s.mean()).tolist()) # [1.0, 2.0, 3.0]
print(s.dropna().tolist()) # [1.0, 3.0]fillna replaces missing entries with a value you choose. Here that value is the mean. dropna removes them. Both return new objects and leave s unchanged.
Counting missing values per column
On a DataFrame, chain isna() with sum(). Booleans count as 0 and 1, so the sum is the number of missing entries in each column.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune"],
"pop_m": [0.7, None, 3.1],
"region": ["EU", "SA", None],
})
print(df.isna().sum())
print(df.dropna(subset=["pop_m"]))
print(df.fillna({"pop_m": df["pop_m"].median(), "region": "unknown"}))Three things to note:
dropna()with no arguments drops every row that has any missing value. Usesubsetto limit the check to the columns that matter.fillnaaccepts a dictionary, so each column can get its own replacement.- Many aggregations skip
NaNby default.df["pop_m"].mean()averages only the two present values. Passskipna=Falseif you wantNaNto propagate.
Choosing a strategy
| Situation | Reasonable choice |
|---|---|
| Few rows affected, column is essential | `dropna(subset=[...])` |
| Numeric column, missing means "typical" | `fillna` with mean or median |
| Missing means zero, such as no sales | `fillna(0)` |
| Missing is meaningful | Keep it, or add a flag column with `isna()` |
Exercise
Given s = pd.Series([4.0, None, 6.0, None]), what do s.mean() and s.fillna(0).mean() return?
Show answer
s.mean() returns 5.0, because it skips the two missing values and averages 4 and 6. s.fillna(0).mean() returns 2.5, because the missing values become 0 and the sum 10 is divided by 4 entries. Filling changes the statistic, so pick the fill value deliberately.
Exercise
Why does df["pop_m"] == float("nan") select no rows, and what should you use instead?
Show answer
NaN is not equal to any value, including itself, so the comparison is False for every row. Use df["pop_m"].isna() to build the mask.