Sub topic 9
Filtering Rows with Missing Values
This chapter assumes you can build a DataFrame from a dictionary, write a boolean mask, and combine masks with &, |, and ~. Here you will apply those skills to rows where a value is missing.
How pandas stores missing values
pandas marks a missing value in a numeric column as NaN, which stands for "not a number". In object columns, a missing value can be None or NaN. Newer nullable dtypes use pd.NA. All of these count as missing.
Here is a small DataFrame with one gap:
import pandas as pd
scores = pd.DataFrame({"name": ["x", "y", "z"], "score": [1.0, None, 3.0]})
print(scores)
print(scores.dtypes)The None in score becomes NaN, and the column dtype is float64. Integers cannot hold NaN in a plain NumPy column, so a numeric column with gaps is converted to float.
Why == does not work
NaN is not equal to anything, including itself. A comparison with == therefore returns False for every row, and the missing rows are never matched.
import pandas as pd
scores = pd.DataFrame({"name": ["x", "y", "z"], "score": [1.0, None, 3.0]})
print(scores["score"] == float("nan"))
print(scores["score"] != scores["score"])The first line prints False for all three rows. The second line is a trick that shows the same fact from the other side: only the missing row is not equal to itself. You should not rely on that trick. Use the dedicated methods instead.
Building masks with isna and notna
isna() returns True where a value is missing. notna() returns True where a value is present. Both return a boolean Series that you can use as a row mask.
import pandas as pd
scores = pd.DataFrame({"name": ["x", "y", "z"], "score": [1.0, None, 3.0]})
print(scores[scores["score"].notna()])
print(scores[scores["score"].isna()])The first call keeps rows x and z. The second keeps only row y. The names isnull() and notnull() are aliases for the same methods.
Combining missing-value masks with other conditions
Missing-value masks behave like any other mask. Put each one in its own variable or in parentheses, then combine them.
import pandas as pd
scores = pd.DataFrame(
{
"name": ["x", "y", "z", "w"],
"score": [1.0, None, 3.0, None],
"team": ["red", "red", "blue", "blue"],
}
)
missing = scores["score"].isna()
red = scores["team"] == "red"
print(scores[missing & red])
print(scores[~missing & red])The first line finds red-team rows with no score. The second finds red-team rows that have one. Writing ~missing is the same as writing scores["score"].notna().
Checking several columns at once
Calling isna() on a whole DataFrame returns a DataFrame of booleans. Reduce it to one value per row with any or all.
import pandas as pd
df = pd.DataFrame(
{
"a": [1.0, None, 3.0],
"b": [4.0, 5.0, None],
}
)
print(df[df.isna().any(axis=1)])
print(df[df.notna().all(axis=1)])With axis=1, any checks across the columns of each row. The first line keeps rows with at least one gap. The second keeps only complete rows.
When your goal is simply to drop incomplete rows, dropna is shorter. It also accepts subset to look at only some columns.
import pandas as pd
df = pd.DataFrame(
{
"a": [1.0, None, 3.0],
"b": [4.0, 5.0, None],
}
)
print(df.dropna())
print(df.dropna(subset=["a"]))Common errors
- Writing
df[df["score"] == None]or== np.nan. Neither selects missing rows. Useisna(). - Writing
df["score"].isna() & df["team"] == "red"without parentheses. The==binds more loosely than&, so the expression fails or gives a wrong result. Use variables or parentheses. - Using
andororbetween masks. Python raises aValueErrorbecause a Series has no single truth value. Use&and|. - Assuming a numeric filter keeps rows with gaps. It does not. Add
| df["score"].isna()if you want them.
Exercise
A DataFrame df has a numeric column price with some missing values. Write one expression that returns the rows where price is either missing or greater than 100.
Show answer
df[df["price"].isna() | (df["price"] > 100)]. The comparison alone would drop the missing rows, so the isna() mask is combined with |. The comparison needs parentheses only if it is written inline, as here.
Exercise
Why does df[df["score"] == float("nan")] return an empty DataFrame even when score contains missing values?
Show answer
NaN is not equal to any value, including itself, so the comparison is False for every row. Use df[df["score"].isna()] instead.