Sub topic 8
Counting distinct values with nunique
This chapter assumes you can create a DataFrame, select a column, and that you know unique returns the distinct values of a column. It builds on how pandas treats missing values in counts.
What nunique returns
nunique returns the number of distinct values in a Series. It answers "how many different items are there?" instead of "what are they?" or "how often does each occur?".
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
print(df["city"].nunique()) # 3
print(df["city"].nunique(dropna=False)) # 4
print(df["city"].count()) # 6The column holds Oslo, Rome and Paris, so the default result is 3. The missing value in the last row is ignored.
Missing values and dropna
By default nunique has dropna=True, so missing values are not counted as a distinct item. With dropna=False, the missing value counts as one more distinct item, and the result becomes 4.
This differs from unique, which always includes the missing value in its output. That gives a useful check:
print(len(df["city"].unique())) # 4, includes the missing value
print(df["city"].nunique()) # 3len(unique()) equals nunique(dropna=False). It equals plain nunique() only when the column has no missing values.
nunique, count and size
These three are often confused.
| Method | Question it answers | `city` result |
|---|---|---|
| `count()` | How many non-missing entries? | 6 |
| `nunique()` | How many different non-missing values? | 3 |
| `len(df)` | How many rows in total? | 7 |
count is always greater than or equal to nunique. If the two are equal, every non-missing value appears exactly once.
nunique on a whole DataFrame
Calling nunique on a DataFrame returns a Series with one distinct count per column. This is a quick way to profile a table.
print(df.nunique())
# city 3
# plan 2
# dtype: int64A column with very few distinct values, such as plan, is a candidate for a categorical type. A column where nunique equals the number of rows may be an identifier.
Distinct counts per group
Combine groupby with nunique to count distinct values inside each group.
print(df.groupby("plan")["city"].nunique())
# plan
# free 1
# pro 3
# Name: city, dtype: int64The free plan has one distinct city (Oslo). The pro plan has three. Compare this with count, which gives 2 and 4 for the same groups, because it counts non-missing entries and not distinct ones.
Common errors
- Expecting the missing value to be counted. Pass
dropna=Falseif it should be. - Using
nuniquewhen you want a frequency table. Usevalue_countsfor that. - Calling
nuniqueon a column that holds lists or dictionaries. These values are not hashable, so pandas raises aTypeError.
Exercise
A column status has the values ["a", "b", "a", None, "c", None]. What do nunique(), nunique(dropna=False) and count() return?
Show answer
nunique() returns 3 (a, b, c). nunique(dropna=False) returns 4, because the missing value counts as one distinct item. count() returns 4, the number of non-missing entries (a, b, a, c).