Sub topic 2
How Missing Values Affect Counts
This chapter assumes you can build a pandas Series and DataFrame, select a column, and read basic Python. Counting methods in pandas do not all handle missing values the same way. Some skip them, some report them, and some treat them as ordinary values. Knowing which is which keeps your totals and percentages correct.
What pandas treats as missing
A missing value marks data that is absent. In a column of text, None is stored as a missing value. In a numeric column it becomes NaN ("not a number"). Pandas also has pd.NA, a missing marker used by its nullable data types. The isna() method recognizes all of these.
Two points matter for counting:
- Only real missing markers count as missing. An empty string
""or the text"n/a"is a normal value, and pandas counts it like any other. - An integer column that contains
NaNis stored as floats by default, so the numbers1and2appear as1.0and2.0.
The examples in this chapter use the same DataFrame throughout:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
n_rows = len(df) # 7, every row
n_missing = df["city"].isna().sum() # 1
n_present = df["city"].notna().sum() # 6The city column has seven entries and one is missing. Keep the numbers 7, 6, and 1 in mind, because each counting method returns one of them or a value built from them.
Defaults at a glance
| Method | Missing values by default | How to change it |
|---|---|---|
| `Series.value_counts()` | Left out of the result | `dropna=False` |
| `Series.nunique()` | Not counted | `dropna=False` |
| `Series.unique()` | Included as one item | `.dropna().unique()` |
| `Series.count()` | Not counted | No option, it always skips them |
| `len(s)` and `s.size` | Counted | No option, they count every entry |
| `duplicated()` and `drop_duplicates()` | Treated as equal to each other | No option |
| `groupby(...)` keys | Rows with a missing key are dropped | `dropna=False` |
Most of the confusion comes from unique. It is the one method here that shows missing values while the others skip them.
Counting with and without missing values
value_counts skips missing values unless you ask for them:
counts = df["city"].value_counts()
# Oslo 3
# Rome 2
# Paris 1
with_missing = df["city"].value_counts(dropna=False)
# Oslo 3
# Rome 2
# Paris 1
# NaN 1 (the label for the missing value)The default result adds up to 6, not 7. If you sum the counts and compare with len(df), the difference is the number of missing values. This is a quick check that every row is accounted for.
The count method follows the same rule as value_counts and ignores missing values:
df["city"].count() # 6
df["city"].size # 7count() and len() look similar but answer different questions. count() asks how many entries have data, and len() asks how many entries exist. A column with no gaps gives the same number for both.
Distinct values and missing values
unique returns the distinct values in order of first appearance, and the missing value is one of them. nunique counts distinct values and skips missing ones by default:
df["city"].unique() # ['Oslo', 'Rome', 'Paris', None]
df["city"].nunique() # 3
df["city"].nunique(dropna=False) # 4
len(df["city"].unique()) # 4, matches nunique(dropna=False)This produces a common bug. If you write len(s.unique()) expecting the same result as s.nunique(), you get one more whenever the column has a gap. Pick one approach and match its missing-value behavior to your question. If you want to list the real categories only, remove the gaps first:
df["city"].dropna().unique() # ['Oslo', 'Rome', 'Paris']Proportions and the denominator
The normalize=True option divides each count by a total. That total depends on dropna, so the same data gives different percentages:
df["city"].value_counts(normalize=True)
# Oslo 0.500000 (3 / 6)
# Rome 0.333333 (2 / 6)
# Paris 0.166667 (1 / 6)
df["city"].value_counts(normalize=True, dropna=False)
# Oslo 0.428571 (3 / 7)
# Rome 0.285714 (2 / 7)
# Paris 0.142857 (1 / 7)
# NaN 0.142857 (1 / 7)With the default, the shares add up to 1 over the known cities only. With dropna=False, they add up to 1 over all rows. Neither is wrong, and they answer different questions. "Among customers who gave a city, what share live in Oslo?" uses the default. "What share of all customers are Oslo customers?" needs dropna=False. State which one you mean whenever you report a percentage.
Duplicates and missing values
Missing values are not equal to each other in ordinary Python. float("nan") == float("nan") is False. Pandas works differently for duplicate detection: two missing values in the same position count as the same value.
s = pd.Series(["Oslo", None, "Rome", None])
s.duplicated()
# 0 False
# 1 False
# 2 False
# 3 True (the second missing value repeats the first)The same rule applies to drop_duplicates, which would keep one of the two missing entries. When you compare rows over several columns, a row with a missing value matches another row only if the other values match and that position is also missing. If you do not want missing entries to collapse into one, fill them with distinct placeholders first or drop those rows.
Gaps that pandas cannot see
Pandas only reports a gap if it is stored as a missing marker. Data from spreadsheets and exports often uses other signs for "no data":
import pandas as pd
raw = pd.Series(["Oslo", "", "n/a", None, "Oslo"])
raw.value_counts()
# Oslo 2
# 1 (the empty string)
# n/a 1
cleaned = raw.mask(raw.isin(["", "n/a"]))
cleaned.value_counts()
# Oslo 2
cleaned.isna().sum() # 3Before mask, the empty string and "n/a" appear as two extra categories, which inflates nunique and shifts every proportion. mask replaces the listed values with NaN, so the counting methods can handle them as missing. Do this cleanup before you count, not after.
Choosing a behavior
The decision depends on what the missing value means in your data. The flowchart below summarizes the choices for a frequency count.
Common mistakes
- Reading
value_counts()totals as the row count. They matchcount(), notlen(). - Using
len(s.unique())and comparing it tonunique(). They differ by one when a missing value is present. - Reporting a percentage without saying whether missing rows are in the denominator.
- Trusting
isna()on data that uses""or"unknown"for gaps. - Expecting a
groupbyon a column with gaps to keep those rows. By default, rows with a missing group key vanish from the result. Passdropna=Falsetogroupbyto keep them as their own group.
Exercise
A column s has 10 entries. Two are missing, four are "a", and four are "b". What do s.value_counts(normalize=True) and s.value_counts(normalize=True, dropna=False) return for "a", and what does len(s.unique()) return?
Show answer
The default gives "a" a share of 4/8 = 0.5, because the two missing entries are left out of the total. With dropna=False the share is 4/10 = 0.4, and the missing value gets its own entry with 0.2. len(s.unique()) is 3: "a", "b", and one missing value.
Exercise
A Series contains ["x", None, None, "x"]. How many rows does duplicated() mark as True, and which ones?
Show answer
Two. Row 2 (the second missing value) repeats row 1, and row 3 ("x") repeats row 0. Pandas treats missing values as equal to each other when it looks for duplicates.