Sub topic 10
Finding and handling missing values
This chapter assumes you can build a Series and a DataFrame, select with loc and boolean masks, and know that arithmetic aligns on the index. Real tables have gaps, and pandas has specific rules for how it stores, skips, and propagates them. Knowing those rules keeps a quietly wrong average from reaching your report.
How pandas represents "missing"
pandas uses a few markers, depending on the dtype:
| Marker | Where it appears | Notes |
|---|---|---|
| `NaN` (`np.nan`) | float columns | The default for numeric data. |
| `None` | object columns | Kept as `None`, but treated as missing. |
| `NaT` | datetime columns | "Not a time". |
| `pd.NA` | nullable dtypes such as `Int64`, `string`, `boolean` | A dedicated missing value that keeps the integer dtype. |
import numpy as np
import pandas as pd
print(pd.Series([1, None, 3]).dtype) # float64
print(pd.Series(["a", None, "c"]).dtype) # object
print(pd.Series([1, None, 3], dtype="Int64").tolist()) # [1, <NA>, 3]The first line shows a common surprise. An integer column that gains a missing value becomes float64, because NaN is a float and plain NumPy integers cannot hold it. The nullable Int64 dtype avoids this and keeps the values as integers.
Finding missing values
isna() returns a boolean object of the same shape. notna() is its inverse. Because booleans sum as 0 and 1, you can count gaps with sum().
import numpy as np
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, np.nan, 3.1, 2.8],
"region": ["EU", "SA", None, "EU"],
})
print(df.isna().sum()) # missing count per column
print(df.isna().mean()) # fraction missing per column
print(df[df["pop_m"].isna()]) # rows where pop_m is missing
print(df[df.isna().any(axis=1)]) # rows with any missing valuedf.isna().sum() gives city 0, pop_m 1, region 1. The last line uses any(axis=1) to collapse each row's booleans into one value, so it selects the Lima and Pune rows. For a quick overview, df.info() shows non-null counts per column.
Filling missing values
fillna replaces missing entries and returns a new object. The original is unchanged unless you assign the result back.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, np.nan, 3.1, 2.8],
"region": ["EU", "SA", None, "EU"],
})
filled_mean = df["pop_m"].fillna(df["pop_m"].mean())
print(filled_mean.round(2).tolist()) # [0.7, 2.2, 3.1, 2.8]
per_column = df.fillna({"pop_m": 0, "region": "unknown"})
print(per_column)Passing a dictionary lets you choose a different fill value for each column. This matters because a single scalar rarely suits every column. A 0 makes sense for a count, while "unknown" makes sense for a label.
For ordered data such as time series, fill from neighbors instead:
import pandas as pd
s = pd.Series([1.0, None, None, 4.0])
print(s.ffill().tolist()) # [1.0, 1.0, 1.0, 4.0] carry last value forward
print(s.bfill().tolist()) # [1.0, 4.0, 4.0, 4.0] pull next value backwardForward fill assumes that the last known value is still true. That is reasonable for a sensor reading and wrong for something like a daily sales total.
Dropping missing values
dropna removes rows (the default) or columns that contain missing data. Three parameters control how aggressive it is:
how="any"(default) drops a row if any value is missing.how="all"drops it only if every value is missing.subset=[...]limits the check to the listed columns.thresh=nkeeps only rows that have at leastnnon-missing values.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, np.nan, 3.1, 2.8],
"region": ["EU", "SA", None, "EU"],
})
print(df.dropna(subset=["pop_m"])) # drops Lima only
print(df.dropna(thresh=3)) # keeps Oslo and Rome
print(df.dropna(axis=1)) # drops pop_m and region columnsPrefer subset in most cases. A plain df.dropna() can discard a row because of a gap in a column you never use.
Choosing a strategy
Sentinel values from files
Files often encode "unknown" as -999, "missing", or an empty-looking string. pandas will treat these as ordinary data unless you say otherwise, and a -999 population will quietly ruin a mean. Convert them at load time with na_values:
import io
import pandas as pd
data = "city,pop_m\nOslo,0.7\nLima,-999\nPune,missing\nRome,2.8\n"
df = pd.read_csv(io.StringIO(data), na_values=["-999", "missing"])
print(df["pop_m"].dtype) # float64
print(df["pop_m"].isna().sum()) # 2Without na_values, the text missing would force the whole column to object, and arithmetic would fail. For data already in memory, use df.replace(-999, np.nan) instead.
How missing values behave in calculations
Most reductions skip missing values by default, and that can hide problems.
import pandas as pd
s = pd.Series([1.0, None, 3.0])
print(s.sum()) # 4.0
print(s.mean()) # 2.0, divides by 2, not 3
print(s.sum(skipna=False)) # nan
print(s.count()) # 2, counts non-missing only
print(len(s)) # 3mean() divides by the number of non-missing values. That is often what you want, but it means the average describes only the rows that had data. Compare count() with len() when you need to know how much data stands behind a statistic.
Comparisons and masks have a related trap. df["pop_m"] > 3 is False for a missing value, so a filter silently drops those rows. They are not "not greater than 3". They are unknown. If gaps matter, add an explicit check such as df["pop_m"].isna() | (df["pop_m"] > 3).
Missing values also interact with index alignment. In the earlier chapter, a + b produced NaN for labels present on only one side. The same cleanup tools apply to those results, and a.add(b, fill_value=0) avoids creating the gaps in the first place.
Common mistakes
- Forgetting to assign.
df.fillna(0)returns a new frame. Writedf = df.fillna(0)or assign a single column. - Using
inplace=Trueon a column selection.df["pop_m"].fillna(0, inplace=True)may operate on a temporary copy and leavedfunchanged. Assign the result back to the column instead. - Filling before splitting data. If you compute a mean fill value on all rows, then split into training and test sets, information leaks between them. Compute fill statistics on the training portion only.
- Filling with a value that looks real. Filling a count column with
0states that nothing happened, which may be false. Sometimes leavingNaNis the honest choice. - Dropping silently. Check
len(df)before and afterdropna, so you know how much data you removed.
Exercise
A DataFrame df has a float column score with 2 missing values out of 10 rows. You run df["score"].mean() and get 70.0. A colleague then runs df["score"].fillna(0).mean(). Will the second result be higher, lower, or equal to 70.0, and why?
Show answer
Lower. The first mean skips the 2 missing values and divides the sum by 8. The second replaces them with 0, so the sum stays the same but is divided by 10. The result is 70.0 * 8 / 10 = 56.0. Filling with 0 treats unknown scores as zero scores, which changes the meaning of the statistic.