Sub topic 9
Filtering rows with missing values
This chapter assumes you can build a DataFrame, use boolean masks with &, | and ~, and use .loc for selection. It covers why missing values behave differently from other values in a filter, and which tools to use for them.
How pandas marks missing data
pandas uses several markers for "no value here". Which one you see depends on the column's dtype.
| Marker | Typical column dtype | Notes |
|---|---|---|
| `np.nan` | `float64`, and object columns | A float, so an integer column with gaps becomes `float64`. |
| `None` | `object` | Kept as `None` in object columns. |
| `pd.NA` | Nullable types such as `Int64`, `boolean`, `string` | Used by the nullable extension dtypes. |
| `pd.NaT` | `datetime64` and `timedelta64` | The missing marker for time values. |
isna() and notna() recognize all four, so you rarely need to care which marker a column holds.
The examples below use this DataFrame. It has missing values in a numeric column and in a text column.
import numpy as np
import pandas as pd
scores = pd.DataFrame(
{
"name": ["x", "y", "z", "w", "v"],
"score": [1.0, None, 3.0, np.nan, np.nan],
"group": ["a", "b", None, "a", None],
}
)
print(scores.dtypes)
print(scores.isna())
print(scores.isna().sum())scores.isna() returns a DataFrame of booleans with the same shape. Calling .sum() on it counts the True values in each column, which gives you the number of missing values per column. Do this first on any new dataset, because it tells you where a filter could go wrong.
Why `== np.nan` finds nothing
Missing values are not equal to anything, including themselves. A comparison that involves NaN returns False.
print(scores["score"] == np.nan)
print(scores["score"] != scores["score"])The first line returns False for every row, including the three rows where the score is missing. The second line returns True only for the missing rows. That works because NaN != NaN is True, but it is hard to read. Use the named methods instead.
print(scores[scores["score"].notna()])
print(scores[scores["score"].isna()])The first line keeps rows x and z. The second keeps y, w and v. isna and notna are inverses, so ~s.isna() and s.notna() select the same rows. Choose whichever reads better in context.
Comparisons silently exclude missing rows
Any ordinary comparison, such as >, <= or ==, gives False on a missing value. That has a consequence when you negate a mask.
high = scores["score"] > 2
print(high.tolist()) # [False, False, True, False, False]
print(scores[~high]) # rows x, y, w, v: includes the NaN rows
print(scores[scores["score"] <= 2]) # row x only~high means "not high", and a missing score counts as "not high" because the comparison returned False. The expression score <= 2 returns False for missing scores as well, so it keeps only row x. These two filters look like they ask the same question, but they return different rows. Decide what you want for missing rows, then write it explicitly.
low_known = scores["score"].notna() & (scores["score"] <= 2)
low_or_unknown = scores["score"].isna() | (scores["score"] <= 2)
print(scores[low_known])
print(scores[low_or_unknown])The first mask keeps only x. The second keeps x, y, w and v.
The same issue applies to text and equality tests on object columns.
print(scores[scores["group"] != "a"])This returns rows y, z and v. Rows z and v appear because None != "a" is True. If you meant "has a group and it is not a", combine the test with notna().
print(scores[scores["group"].notna() & (scores["group"] != "a")])This returns only row y.
String methods and missing values
The .str methods return a missing value where the input is missing. In an object column, that makes the result unusable as a mask.
# Raises ValueError: Cannot mask with non-boolean array containing NA / NaN values
# scores[scores["group"].str.startswith("a")]
print(scores[scores["group"].str.startswith("a", na=False)])Most .str predicates, including startswith, endswith and contains, accept an na argument. With na=False, a missing value counts as "no match", and the result is a plain boolean Series. Pass na=True if you want missing rows to be included. The example above returns rows x and w.
Filtering across several columns
Add axis=1 to ask row-wise questions about the whole DataFrame.
any_missing = scores.isna().any(axis=1)
complete = scores.notna().all(axis=1)
print(scores[any_missing])
print(scores[complete])any(axis=1) is True for a row if at least one of its cells is missing. all(axis=1) on notna() is True only when every cell has a value. In this data, complete keeps only row x.
To restrict the check to some columns, select them first.
print(scores[scores[["score", "group"]].isna().all(axis=1)])This returns row v, the only row where both score and group are missing.
Dropping rows with `dropna`
When you want to remove incomplete rows rather than inspect them, dropna is shorter than building a mask. It returns a new DataFrame and leaves the original unchanged.
print(scores.dropna()) # row x only
print(scores.dropna(subset=["score"])) # rows x, z
print(scores.dropna(how="all", subset=["score", "group"])) # drops v only
print(scores.dropna(thresh=2)) # drops v onlysubsetlimits the check to the listed columns. Without it,dropnalooks at every column, so one gap in an unimportant column removes the row.how="any"is the default and drops a row if any checked cell is missing.how="all"drops it only if every checked cell is missing.thresh=Nkeeps rows that have at least N non-missing values among the checked columns. It cannot be combined withhow.
A mask gives you more control, and you can combine it with other conditions. dropna is clearer when the rule is simply "complete rows only".
Nullable dtypes and `pd.NA`
Columns with nullable dtypes such as Int64 use pd.NA. A comparison with pd.NA returns <NA> rather than False, and the result has the boolean dtype.
ages = pd.Series([25, pd.NA, 40], dtype="Int64")
mask = ages > 30
print(mask)
print(ages[mask])mask holds False, <NA> and True. When you index with it, <NA> is treated as False, so ages[mask] returns only the value 40. Combining masks follows three-valued logic. False & <NA> is False, but True & <NA> stays <NA>. This matters little with a final filter, because <NA> is dropped anyway. It does matter if you store the mask and reuse it. Call fillna(False) on the mask when you need a strict two-valued result.
Common mistakes
- Writing
df[df["col"] == None]ordf[df["col"] == np.nan]. Both return no rows. Useisna(). - Negating a comparison and expecting missing rows to be excluded.
~(s > 2)includes them. - Calling
.strmethods in a mask withoutna=False. This raises aValueErroron object columns that contain missing values. - Using bare
dropna()on a wide table. One mostly empty column can remove nearly every row. Passsubset. - Forgetting that integer columns with
NaNbecomefloat64. A value of3.0is still equal to3, but dtype checks and merges can surprise you.
Exercise
Using the scores DataFrame from this chapter, write one expression that returns the rows where score is greater than 2 or score is missing. Which rows does it return?
Show answer
scores[scores["score"].isna() | (scores["score"] > 2)]. It returns rows z, y, w and v. Row z has score 3.0, and rows y, w and v have a missing score. The parentheses around the comparison are needed because | binds more tightly than >.
Exercise
Why does scores[scores["group"].str.contains("a")] fail, and how do you fix it so that rows with a missing group are left out?
Show answer
The group column holds None, so .str.contains returns a missing value for those rows. The result is not a pure boolean mask, and indexing with it raises a ValueError. Pass na=False: scores[scores["group"].str.contains("a", na=False)]. This returns rows x, y (group "b" does not contain "a", so it is excluded) and w, which means the final result is rows x and w.