Sub topic 2
Finding missing values
This chapter covers how to locate missing values in a Series or DataFrame, count them, and turn the result into filters and a short report. It assumes you can build and index a Series and DataFrame, that you know np.nan, and that you have seen the missing markers pandas uses: NaN, None, NaT and pd.NA. It does not change any data. Dropping and filling come in later chapters.
The two core methods
isna takes a Series or DataFrame and returns a same-shaped object of booleans. True marks a missing cell. notna is the exact inverse. The older names isnull and notnull are aliases, so use whichever your codebase already uses and stay consistent.
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 the mask:
name age city
0 False False False
1 False True True
2 False False False
3 False True FalseThe second adds up the True values in each column, because True counts as 1 when summed:
name 0
age 2
city 1
dtype: int64Notice that None in the city column and np.nan in the age column are both flagged. isna treats every missing marker the same way, so you do not need to know which marker a given cell holds.
Counting missing values
Most questions about missing data reduce the mask with an aggregation. The axis you choose decides what you learn.
| Expression | What it tells you |
|---|---|
| `df.isna().sum()` | Missing count per column |
| `df.isna().mean()` | Fraction missing per column (0 to 1) |
| `df.isna().sum(axis=1)` | Missing count per row |
| `df.isna().sum().sum()` | Total missing cells |
| `df.isna().any()` | Columns with at least one missing value |
| `df.isna().any(axis=1)` | Rows with at least one missing value |
| `df.isna().all()` | Columns that are entirely missing |
| `df.count()` | Non-missing count per column |
count goes the other way from isna().sum(): it reports the non-missing cells. len(df) - df.count() gives the same result as df.isna().sum(). Also, df.info() prints a "Non-Null Count" for each column. That is a quick first look at a new dataset, but it gives you nothing to index or filter with.
The fraction from mean is often more useful than the count. Two missing values in four rows is very different from two in four million.
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().mean())
print(df.isna().sum(axis=1))
print(df.count())Row counts are useful for spotting records that are mostly empty. df.isna().sum(axis=1).value_counts().sort_index() summarizes how many rows have zero, one, two, and so on, missing cells.
Selecting rows by missingness
Because the mask is a boolean object, you can pass it to [] or .loc to select rows. This is how you look at the records behind a count.
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[df["age"].isna()])
print(df[df.isna().any(axis=1)])
print(df[df["age"].notna() & df["city"].notna()])The first line selects rows where age is missing (Ben and Dee). The second selects rows with any missing cell, and here also returns Ben and Dee. The third combines two notna masks with & and keeps only rows where both columns are present (Ana and Cy). When you combine masks, wrap each condition in parentheses if it contains a comparison, because & binds more tightly than > or ==.
Reading the rows that are missing is often more informative than the count. If every missing age belongs to one source system or one date range, that points to a cause rather than random noise. A later chapter on why data is missing builds on this.
Why `== np.nan` does not work
A common mistake is to test for missing values with equality.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0])
print(s == np.nan)
print(s.isna())s == np.nan returns False for every element. By the IEEE 754 floating-point rules, NaN is not equal to anything, including itself. The comparison never matches, and no error warns you. Always use isna. The same applies to is None checks on a column: they test the Series object, not its cells.
What isna does not flag
isna detects the real missing markers only. Anything that merely looks like "no data" is an ordinary value to it.
import numpy as np
import pandas as pd
s = pd.Series(["a", "", " ", "NA", "-999", None])
print(s.isna())
nums = pd.Series([1.0, np.inf, -np.inf, np.nan])
print(nums.isna())In the first Series, only the final entry (None) is True. The empty string, the blank, the text "NA" and the text "-999" are all valid strings. In the second, only np.nan is flagged. Infinity is a legitimate float, so isna ignores it.
You find these hidden placeholders by looking at the data itself:
s.value_counts(dropna=False)lists every distinct value, including missing ones. Suspicious entries tend to appear near the top.s.str.strip().eq("").sum()counts empty or whitespace-only strings. Missing entries stayNaNhere and compare asFalse, so they are not counted.np.isinf(nums).sum()counts infinite values in a numeric column.df.describe()shows a minimum such as-999or a maximum such as9999that no real measurement would produce.
Detection for other types
The same methods work across dtypes. Datetime columns use NaT, and nullable dtypes use pd.NA. You call isna the same way.
import pandas as pd
dates = pd.Series(pd.to_datetime(["2024-01-01", None, "2024-03-05"]))
print(dates.isna())
counts = pd.Series([1, None, 3], dtype="Int64")
print(counts.isna())
print(counts.count())Both Series report the middle element as missing. Because counts uses the nullable Int64 dtype, the other values stay integers instead of being converted to floats. The dtype only changes how the data is stored. Detection works the same way.
Building a missingness report
When you start on an unfamiliar dataset, the count and the fraction together answer the first question: which columns need attention? A small function keeps that check repeatable.
import numpy as np
import pandas as pd
def missing_report(df):
report = pd.DataFrame({
"missing": df.isna().sum(),
"percent": (df.isna().mean() * 100).round(1),
})
return report.sort_values("missing", ascending=False)
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
print(missing_report(df))The output is:
missing percent
age 2 50.0
city 1 25.0
name 0 0.0Sorting puts the worst columns first. You can extend the function with a dtype column from df.dtypes or with the number of distinct values from df.nunique(), but keep it small enough that you run it every time you load data.
Common mistakes when detecting
- Using
== np.nanor!= np.naninstead ofisnaandnotna. - Calling
.sum()on the DataFrame instead of on the mask, which adds up the data rather than counting missing cells. - Forgetting
axis=1when you want a per-row result, then getting a per-column one. - Trusting
isnaon a column that holds placeholders such as"","N/A"or-999. - Combining masks with
andororinstead of&and|. Python's keywords raise aValueErroron a Series, because the truth value of a Series is ambiguous. - Assuming
df.dropna()is a way of looking at missing data. It removes rows and gives you a new object. Use a mask to inspect first.
Exercise
A DataFrame df has columns price and region. Write one expression that returns the rows where price is present but region is missing. Then write one expression that gives the fraction of rows missing region.
Show answer
df[df["price"].notna() & df["region"].isna()] selects the rows. df["region"].isna().mean() gives the fraction, because the mean of a boolean Series is the share of True values. Each condition is a separate boolean Series, so & combines them. and would raise a ValueError.
Exercise
You run df["status"].isna().sum() and get 0, yet you suspect the column has missing data stored as text. Name two checks you could run to find out, and say what each would reveal.
Show answer
Run df["status"].value_counts(dropna=False) to list every distinct value. Entries such as "N/A", "unknown" or an empty string would appear with their counts. Run df["status"].str.strip().eq("").sum() to count empty or whitespace-only strings. isna reports 0 because those entries are ordinary strings, not real missing markers.