Sub topic 13
Distinct counts per group
This chapter assumes you can build a DataFrame, select a column, and call groupby with a single key. You have already seen nunique on a whole column. Here you apply it inside groups and compare it with size and count.
The question this answers
size and count tell you how many rows a group has. They do not tell you how many different values appear in it. For that you use nunique on the grouped column.
The examples use this DataFrame:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
rows_per_plan = df.groupby("plan").size()
cities_per_plan = df.groupby("plan")["city"].count()
distinct_cities = df.groupby("plan")["city"].nunique()
print(rows_per_plan)
print(cities_per_plan)
print(distinct_cities)Reading the three results
| Plan | size | count of city | nunique of city |
|---|---|---|---|
| free | 3 | 2 | 1 |
| pro | 4 | 4 | 3 |
The free group has three rows, one of them with a missing city. size counts all three. count skips the missing value and returns 2. nunique sees only one distinct city, Oslo, because Oslo appears twice and the missing value is ignored.
Including missing values
nunique on a grouped column accepts dropna. With dropna=False, a missing value counts as one more distinct item.
with_missing = df.groupby("plan")["city"].nunique(dropna=False)
print(with_missing) # free 2, pro 3Only free changes, from 1 to 2, because only that group contains a missing city.
Seeing the values, not just the count
When a count looks surprising, list the values. unique on a grouped column returns one array per group.
print(df.groupby("plan")["city"].unique())The free entry includes the missing value, so it holds two items, Oslo and the missing marker. This matches nunique(dropna=False).
Several measures in one table
Named aggregation puts the three measures side by side, which makes the differences easy to compare.
summary = df.groupby("plan").agg(
rows=("city", "size"),
non_missing=("city", "count"),
distinct=("city", "nunique"),
)
print(summary)The result has one row per plan and the columns rows, non_missing and distinct.
Common errors
- Reading
countas a row count. If the column has missing values,countis smaller thansize. Usesizewhen you want rows. - Expecting missing values in
nunique. They are ignored by default. Passdropna=Falseif they should count. - Counting distinct values in the wrong column.
df.groupby("plan").nunique()with no column selected returns a count for every remaining column. Select the one you want first. - Confusing groups with the whole column.
df["city"].nunique()is 3 for the whole data. Per group the counts are 1 and 3, so they do not add up to the total. A city can appear in more than one group.
Exercise
Using the DataFrame above, write code that returns, for each city, the number of distinct plans it appears under, counting only rows where the city is present. What does Rome give?
Show answer
Use df.groupby("city")["plan"].nunique(). Rows with a missing city are dropped from the groups by default. Rome appears only with the pro plan, so it gives 1. Oslo gives 2, because it appears with both free and pro. Paris gives 1.