Sub topic 12
Counting within groups: size versus count
This chapter assumes you can build a DataFrame, select a column, and know that pandas marks missing values as NaN or None. Both size and count work on groups, but they answer different questions.
The core difference
After groupby, each group is a slice of rows. You can ask two things about it:
- How many rows are in the group? Use
size(). - How many non-missing values does a column have in the group? Use
count().
size() counts every row, including rows with missing values. count() skips missing values, and it works column by column.
Worked example
This DataFrame has one missing city.
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)The three results are:
| plan | size | count of city | nunique of city |
|---|---|---|---|
| free | 3 | 2 | 1 |
| pro | 4 | 4 | 3 |
The free group has three rows, but one city is missing. So size reports 3 and count reports 2. The pro group has no missing cities, so both report 4.
Return types and shape
df.groupby("plan").size() returns a Series indexed by the group key. df.groupby("plan").count() returns a DataFrame with one count per remaining column, so it can be wide. To keep the group key as a normal column, use as_index=False or reset_index:
sizes = df.groupby("plan", as_index=False).size()
print(sizes)Here sizes has the columns plan and size.
Choosing between them
- Use
size()to answer "how many records does each group have?" - Use
count()on a column to answer "how many of these records have a value in that column?" - Use
nunique()to answer "how many different values appear in that column?"
A common mistake is calling df.groupby("plan").count() and reading one column as the group size. If that column has missing values, the number is too low. Another is assuming the group key itself is counted when it is missing. By default, groupby drops rows whose key is missing. Pass dropna=False to keep them as their own group.
Exercise
Exercise
Using the DataFrame above, what does df.groupby("plan")["city"].count() minus df.groupby("plan").size() give for the free plan, and what does that number mean?
Show answer
It gives -1, because count is 2 and size is 3. The size minus the count (1) is the number of rows in the free group with a missing city.