Sub topic 13
Distinct counts per group
This chapter covers nunique and unique inside a groupby. It assumes you have read the earlier chapters on count, nunique and groupby().size(). You should be able to create a DataFrame, select a column, and call groupby on it.
Why distinct counts per group
The question "how many rows are in each group?" is answered by size. A different question is "how many different users, products or pages appear in each group?" That is a distinct count per group. The tool for it is nunique, applied to a grouped column.
The examples below use a small event log. Each row is one page view by a user on a plan. One row has a missing page.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "a", "b", "c", "c", "c", "d"],
"plan": ["free", "free", "free", "pro", "pro", "pro", "pro"],
"page": ["home", "docs", "home", "home", "pricing", "docs", None],
})
print(events.groupby("plan")["user"].nunique())The output is:
plan
free 2
pro 2
Name: user, dtype: int64The free plan has three rows but only two distinct users, a and b. The pro plan has four rows and two distinct users, c and d.
How it works
events.groupby("plan")["user"] is a SeriesGroupBy object. Calling nunique() on it counts the distinct values of user separately inside each group and returns a Series indexed by the group keys.
This is the same operation as Series.nunique(), run once per group. The rules from the earlier chapter carry over. Missing values are ignored unless you pass dropna=False.
by_plan = events.groupby("plan")["page"]
print(by_plan.nunique()) # free 2, pro 3
print(by_plan.nunique(dropna=False)) # free 2, pro 4The pro plan has pages home, pricing, docs and one missing value. The default result ignores the missing value and gives 3. With dropna=False the missing value counts as a fourth distinct item.
size, count and nunique side by side
Three methods answer three different questions. The table shows the results for the pro group, with page as the column:
| Method | Question it answers | Pro result for `page` |
|---|---|---|
| `size()` | How many rows are in the group? | 4 |
| `count()` | How many rows have a non-missing value? | 3 |
| `nunique()` | How many different non-missing values are there? | 3 |
| `nunique(dropna=False)` | How many different values, counting missing as one? | 4 |
For the user column in the pro group, size() and count() both give 4, because no user is missing. nunique() gives 2. The gap between count and nunique shows how much repetition the group contains.
Several statistics at once
You usually want rows, distinct users and distinct pages together. Named aggregation produces one table with a column per statistic:
summary = events.groupby("plan").agg(
rows=("user", "size"),
users=("user", "nunique"),
pages=("page", "nunique"),
)
print(summary)The output is:
rows users pages
plan
free 3 2 2
pro 4 2 3Each keyword argument is a pair of the source column and the function name. The strings "size" and "nunique" are both accepted.
You can also call nunique on the whole grouped DataFrame. It returns the distinct count for every column except the grouping key:
print(events.groupby("plan").nunique())This gives user and page columns, and page ignores missing values. It is convenient for exploration, but it computes columns you may not need. Select the columns you want first when the data is large.
Distinct counts per user, and groups with only missing values
You can group by any column, including the one you counted before. This counts the distinct pages each user visited:
pages_per_user = events.groupby("user")["page"].nunique()
print(pages_per_user)The output is:
user
a 2
b 1
c 3
d 0
Name: page, dtype: int64User d has one row, and its page is missing. The group still exists, so the result is 0, not a missing entry. The group is kept because d is a valid key. Only missing values in the key column drop a row from the grouping.
Because the result is an ordinary Series, you can filter it like any other:
multi_page = pages_per_user[pages_per_user > 1]
print(multi_page.index.tolist()) # ['a', 'c']Listing the distinct values per group
nunique gives the count. To see the values themselves, use unique on the grouped column:
print(events.groupby("plan")["page"].unique())The result is a Series with one array per group:
plan
free [home, docs]
pro [home, pricing, docs, None]
Name: page, dtype: objectAs with Series.unique, missing values are not removed. The pro group includes the missing entry, and the values appear in order of first appearance. Compare this with nunique, which drops the missing value by default. If you take len() of one of these arrays, you get the dropna=False count.
If you want one row per distinct pair instead of arrays, drop duplicates before the groupby, or use drop_duplicates on the key and value columns:
pairs = events[["plan", "page"]].drop_duplicates()
print(pairs)Attaching a group-level distinct count to each row
nunique shrinks each group to one number. To keep every row and attach the group's distinct count to it, use transform:
events["users_in_plan"] = events.groupby("plan")["user"].transform("nunique")
print(events[["user", "plan", "users_in_plan"]])Every free row gets 2 and every pro row gets 2. The result has the same length and index as the original DataFrame, so you can assign it as a new column or use it in a filter, for example to keep only rows from plans with more than a given number of distinct users.
Pitfalls
- Missing group keys disappear.
groupbydrops rows whose key is missing, so they appear in no group. Passdropna=Falsetogroupbyif you want a group for them. This is separate from thedropnaargument ofnunique, which concerns the counted values. nuniquecan be slow on large data. It must hash or sort the values in every group. When you only need row counts, usesize.- Categorical keys can show empty groups. If the grouping column has a categorical type,
groupbymay include categories with no rows unless you passobserved=True. Those groups show a distinct count of 0. - Counting pairs is a different task.
groupby(["plan", "page"])["user"].nunique()counts users per plan and page combination. It does not count the pairs themselves. - Duplicates inside a group are not removed.
nuniqueonly reports the count. The original rows are unchanged.
Exercises
Exercise
Using the events DataFrame above, write one expression that returns the number of distinct pages each plan received, counting the missing page as a value. What does it return for each plan?
Show answer
events.groupby("plan")["page"].nunique(dropna=False). The free plan returns 2 (home, docs) and the pro plan returns 4 (home, pricing, docs, and the missing value).
Exercise
For the pro group, size() on page is 4, count() is 3 and nunique() is 3. Explain why count() and nunique() match here, and what you would see if the pro group contained the page home twice with no missing value.
Show answer
count() ignores the one missing value, which gives 3 non-missing entries. All three of those entries are different, so nunique() is also 3. If home appeared twice with no missing value, the group would have 4 non-missing entries but only 3 distinct ones. count() would be 4 and nunique() would be 3.
Exercise
How do you add a column to events that holds, for each row, the number of distinct pages that row's user has visited?
Show answer
events["pages_for_user"] = events.groupby("user")["page"].transform("nunique"). transform returns a result with the same index as events, so each row receives its user's distinct count. User d gets 0 because its only page is missing.