Sub topic 8
Counting distinct values with nunique
Series.nunique answers the question "how many different values does this column hold?" It returns a single integer. This chapter assumes you can build a DataFrame, select a column, and have seen value_counts and unique. It covers how nunique treats missing values, how it differs from count, size and len(unique()), and how to use it per column and per group.
The basic call
The examples use the same small table as the earlier chapters. One city is missing.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
n_cities = df["city"].nunique() # 3: Oslo, Rome, Paris
n_with_missing = df["city"].nunique(dropna=False) # 4: the missing value counts as one item
n_non_null = df["city"].count() # 6: non-missing entries, repeats included
n_rows = len(df["city"]) # 7: every entryThese four numbers answer four different questions:
| Expression | Question it answers | Result |
|---|---|---|
| `nunique()` | How many different non-missing values? | 3 |
| `nunique(dropna=False)` | How many different values, counting missing as one? | 4 |
| `count()` | How many entries are not missing? | 6 |
| `len(s)` | How many entries in total? | 7 |
How missing values are handled
By default dropna=True, so missing values are ignored. With dropna=False, all missing values (None, NaN, NaT, pd.NA) are counted together as one distinct item. A column with 500 missing entries adds exactly 1 to nunique(dropna=False).
The relation to unique follows from this. unique() always includes the missing value, so len(s.unique()) equals s.nunique(dropna=False), not s.nunique().
s = df["city"]
print(len(s.unique())) # 4
print(s.nunique(dropna=False)) # 4, same thing
print(s.nunique()) # 3
print(s.nunique() == s.dropna().nunique()) # TrueA common error is comparing len(s.unique()) with s.nunique() and concluding the column has hidden problems. The difference is the missing value.
What counts as "different"
nunique compares values for exact equality. It does not clean data for you.
raw = pd.Series(["Oslo", "oslo", "Oslo ", "Oslo"])
print(raw.nunique()) # 3
clean = raw.str.strip().str.lower()
print(clean.nunique()) # 1Differences in case or trailing whitespace create separate values, so normalize text before counting if you want to treat variants as the same item. Distinct counts are often inflated by dirty data, and nunique is a quick way to notice.
The values must also be hashable, because pandas uses a hash table internally. A column of lists or dicts fails.
lists = pd.Series([[1, 2], [1, 2], [3]])
try:
lists.nunique()
except TypeError as err:
print(err) # unhashable type: 'list'
print(lists.apply(tuple).nunique()) # 2Converting each list to a tuple makes it hashable.
Applying nunique to a whole DataFrame
DataFrame.nunique returns a Series with one distinct count per column. It also accepts dropna.
print(df.nunique())
# city 3
# plan 2
# dtype: int64
print(df.nunique(dropna=False))
# city 4
# plan 2
# dtype: int64
print(df.nunique(axis=1)) # distinct non-missing values within each rowThis gives a quick profile of a dataset. Dividing by the number of rows gives the share of values that are distinct:
profile = pd.DataFrame({
"distinct": df.nunique(),
"missing": df.isna().sum(),
"distinct_ratio": df.nunique() / len(df),
})
print(profile)A ratio near 1 suggests an identifier. A very small ratio suggests a category, which you might store as a categorical column.
To check whether a column is a valid key, compare its distinct count with the row count, or use the built-in property:
print(df["city"].nunique() == len(df)) # False
print(df["city"].is_unique) # False
print(df["plan"].is_unique) # Falseis_unique treats a missing value like any other value, so two missing entries make it False. Because nunique() ignores missing values by default, the comparison with len(df) fails for a column with any missing entry, even if all other values are different.
Distinct counts per group
After groupby, nunique gives the number of distinct values inside each group. This is the usual tool for questions like "how many different cities does each plan cover?"
rows_per_plan = df.groupby("plan").size() # free 3, pro 4
cities_per_plan = df.groupby("plan")["city"].count() # free 2, pro 4
distinct_cities = df.groupby("plan")["city"].nunique() # free 1, pro 3For the free group, the three rows hold Oslo, Oslo and a missing value. That gives size 3, count 2 and nunique 1. The per-group nunique also accepts dropna=False:
df.groupby("plan")["city"].nunique(dropna=False) # free 2, pro 3Now the missing value counts as a second distinct item in free.
You usually want all three numbers side by side. Named aggregation does that in one call:
summary = df.groupby("plan").agg(
rows=("city", "size"),
non_missing=("city", "count"),
distinct=("city", "nunique"),
)
print(summary)
# rows non_missing distinct
# plan
# free 3 2 1
# pro 4 4 3The relationship distinct <= non_missing <= rows always holds. If distinct equals non_missing, no value repeats inside that group.
Choosing between the tools
Performance and a few edge cases
nuniquebuilds a hash table over the column, so it runs in roughly linear time. On large frames, calling it on one column is cheaper thandf.nunique()on all of them.- Per-group
nuniqueis slower thancountorsizebecause each group needs its own set of seen values. On very large data with many groups, expect it to be the slowest aggregation in your list. - On a column with the
categorydtype,nuniquecounts values that actually occur, not the categories declared in the dtype. Unused categories are not counted. - On an empty Series,
nunique()returns0. - Floating-point values are compared exactly.
0.1 + 0.2and0.3are two distinct values, so round before counting if that matters.
cat = pd.Series(pd.Categorical(["a", "b", "a"], categories=["a", "b", "c"]))
print(cat.nunique()) # 2
print(len(cat.cat.categories)) # 3
floats = pd.Series([0.1 + 0.2, 0.3])
print(floats.nunique()) # 2
print(floats.round(6).nunique()) # 1Common mistakes
- Using
len(s.unique())and expecting it to matchs.nunique(). They differ whenever the column has missing values. - Using
count()when you meannunique().countincludes repeats. - Treating
groupby(...).size()andgroupby(...)[col].count()as the same.sizeincludes missing values andcountdoes not. - Counting distinct values on unclean text without normalizing it first.
- Calling
nuniqueon a column of lists or dicts without converting the items to tuples or strings.
Exercise
A DataFrame has a column user with the values ["a", "b", "a", None, None, "c"]. What do user.nunique(), user.nunique(dropna=False), user.count() and len(user.unique()) return?
Show answer
nunique() returns 3 (a, b, c). nunique(dropna=False) returns 4 because the missing values together count as one item. count() returns 4 because it counts non-missing entries, repeats included (a, b, a, c). len(user.unique()) returns 4 because unique includes the missing value once, so it matches nunique(dropna=False).
Exercise
Write one expression that returns, for each plan in df, the number of distinct cities with the missing value counted as its own item. What does it return for the table in this chapter?
Show answer
df.groupby("plan")["city"].nunique(dropna=False). It returns free 2 (Oslo and the missing value) and pro 3 (Rome, Paris and Oslo).