Sub topic 2
Finding missing values
This chapter assumes you can build a DataFrame and select columns and rows. You should also know that np.nan is NumPy's "not a number" value. The previous chapter covered the markers pandas uses for missing data: NaN, None, NaT and pd.NA. Here you learn how to locate them and measure how much is missing before you decide what to do about it.
Detecting with isna and notna
isna() returns an object of the same shape as the input. Each cell is True where the value is missing. notna() is the exact opposite. Both work on a Series and on a DataFrame, and both recognize every missing marker. isnull() and notnull() are older aliases for the same methods.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
print(df.isna())
print(df.isna().sum())The first print shows a grid of booleans. Rows 1 and 3 are True in the age column, and row 1 is True in the city column. The second print gives the count per column: name 0, age 2, city 1. This works because True counts as 1 when you sum booleans.
Notice that None in city and NaN in age are both detected. You do not need to care which marker is stored.
Counts and proportions
A raw count is hard to judge without the total number of rows. Take the mean of the boolean grid to get the share of missing values per column.
print(df.isna().mean())
print(df.count())
print(df.isna().sum().sum())df.isna().mean()gives the fraction missing per column. Hereageis 0.5 andcityis 0.25.df.count()gives the number of non-missing values per column. It is the complement of the missing count.df.isna().sum().sum()gives the total number of missing cells in the whole table.
df.info() also prints non-null counts per column. It is a quick check, but it prints text instead of returning data you can sort or filter.
Finding the rows that are affected
To see which rows have a problem, collapse the boolean grid across columns with any or all.
has_missing = df[df.isna().any(axis="columns")]
complete = df[df.notna().all(axis="columns")]
missing_age = df[df["age"].isna()]
print(has_missing)
print(complete)
print(missing_age)axis="columns" makes the reduction run across each row. Without it, any() reduces down each column and you get one answer per column instead of one per row.
| Goal | Expression |
|---|---|
| Rows with at least one missing value | `df.isna().any(axis="columns")` |
| Rows with no missing values | `df.notna().all(axis="columns")` |
| Columns with any missing value | `df.isna().any()` |
| Columns that are entirely missing | `df.isna().all()` |
Common errors
Comparing with NaN never works. NaN is not equal to anything, including itself, so df["age"] == np.nan is False in every row. Filtering with it returns an empty result and raises no error. Always use isna().
Placeholders are not detected. isna() only sees real missing markers. An empty string "", the text "unknown", or a number such as -999 counts as ordinary data. If a column's summary looks odd, such as a minimum of -999, check for placeholders before you trust a count of zero missing values. The next chapter shows how to convert them when loading data.
Missing counts depend on dtype. A column of integers with a None becomes float, because plain NumPy integers cannot hold a missing value. The count is still correct, but the column type has changed. A later chapter covers nullable dtypes, which avoid this.
Summary of the workflow
- Run
df.isna().sum()to see where values are missing. - Run
df.isna().mean()to see how serious it is in each column. - Filter with
any(axis="columns")to inspect the affected rows. - Look for placeholders that
isna()cannot see.
Exercise
A DataFrame df has a numeric column score. You run df[df["score"] == np.nan] and get an empty result, even though df["score"].isna().sum() returns 3. Why, and how do you select those three rows?
Show answer
NaN never compares equal to anything, including itself, so == np.nan is False for every row. Use df[df["score"].isna()] to select the three rows with missing scores.