Sub topic 12
Counting within groups: size versus count
This chapter covers how to count rows per group with groupby, and how size, count and nunique differ. It assumes you can build a DataFrame, select a column, and know that pandas marks missing values as NaN or None. It also assumes you have read how value_counts and nunique treat missing values.
The three questions a group can answer
After groupby, each group is a slice of the original rows. You can ask three different questions about a slice:
- How many rows are in it? Use
size. - How many non-missing values does a column have in it? Use
count. - How many different non-missing values does a column have in it? Use
nunique.
The three answers differ whenever a column has missing values or repeated values. 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() # 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 3The free group has three rows. One of them has a missing city, so count returns 2. The two remaining cities are both Oslo, so nunique returns 1.
| Method | Counts | Missing values | Repeated values |
|---|---|---|---|
| `size` | Rows in each group | Included | Counted each time |
| `count` | Non-missing entries of a column | Skipped | Counted each time |
| `nunique` | Distinct non-missing values of a column | Skipped by default | Counted once |
How size works
size belongs to the group, not to a column. It returns the number of rows in each group, so it never looks at missing values in the other columns. On a DataFrameGroupBy it returns a Series indexed by the group keys.
sizes = df.groupby("plan").size()
print(sizes)
# plan
# free 3
# pro 4
# dtype: int64Because the result has no column name, it is common to turn it into a DataFrame with a named column:
sizes_frame = df.groupby("plan").size().reset_index(name="rows")
# plan rows
# 0 free 3
# 1 pro 4
same_frame = df.groupby("plan", as_index=False).size()
# as_index=False names the new column "size" insteadUse reset_index(name=...) when you want to choose the column name yourself.
How count works
count works on columns. It returns, for each group, the number of entries that are not missing. Called on a single column it returns a Series. Called on the whole grouped object it returns one count per remaining column.
per_column = df.groupby("plan").count()
# city
# plan
# free 2
# pro 4The grouping column plan does not appear as a result column, because it is the index. If your DataFrame had ten other columns, you would get ten counts, one per column, and each could differ.
A common error is using count when you mean size. If a column has no missing values, both return the same number and the mistake stays hidden. Later the column gains a missing value and the numbers change without any error. Choose size when you mean "rows", and count only when you mean "filled values".
Counting distinct values with nunique
nunique on a grouped column returns the number of different values in each group. It skips missing values unless you pass dropna=False.
distinct = df.groupby("plan")["city"].nunique()
# free 1, pro 3
distinct_with_missing = df.groupby("plan")["city"].nunique(dropna=False)
# free 2 (Oslo and the missing value), pro 3Use nunique for questions like "how many different customers bought each product". Counting rows would count a customer once per purchase.
Several counts in one table
Named aggregation gives you all three counts in one result, with column names of your choice. It uses the form new_name=(column, function).
summary = df.groupby("plan").agg(
rows=("city", "size"),
filled=("city", "count"),
distinct=("city", "nunique"),
)
# rows filled distinct
# plan
# free 3 2 1
# pro 4 4 3Here size is applied to the city column, but it still reports all rows in the group. The column choice only matters for count and nunique. Putting the three counts side by side makes missing and repeated values easy to see. A large gap between rows and filled means many missing values. A large gap between filled and distinct means many repeats.
Group keys that are missing
By default groupby drops rows whose group key is missing. Those rows do not appear in any group, so size does not count them.
by_city = df.groupby("city").size()
# Oslo 3, Paris 1, Rome 2 (6 rows, the missing city is dropped)
by_city_all = df.groupby("city", dropna=False).size()
# Oslo 3, Paris 1, Rome 2, NaN 1 (all 7 rows)If the group sizes should add up to the length of the DataFrame, pass dropna=False. You can check with by_city_all.sum() == len(df). This is a different effect from the dropna argument of nunique. One decides which rows form groups. The other decides whether a missing value in the counted column counts as a distinct item.
Counting values within each group
To get a frequency table for each group, call value_counts on the grouped column. The result has a MultiIndex of group and value.
per_group_cities = df.groupby("plan")["city"].value_counts()
# plan city
# free Oslo 2
# pro Rome 2
# Oslo 1
# Paris 1Within each group the counts are sorted from most to least frequent. Missing values are left out unless you pass dropna=False. Use this when you need the counts per value, and use nunique when you only need how many different values there are.
Gotchas
- Categorical group keys. If the grouping column has a categorical dtype,
groupbycan list categories that never occur, with a size of 0. Passobserved=Trueto show only categories that occur, orobserved=Falseto show all of them. Setting it explicitly keeps results stable across pandas versions. - Result is a Series or a DataFrame.
size()returns a Series by default. Withas_index=Falseit returns a DataFrame. Code that follows it with.reset_index()can break if you change one without the other. - Counting a key column.
df.groupby("plan")["plan"].count()works, but it only repeatssizeand hides your intent. Usesize. - Index alignment. If you assign a grouped count back to the DataFrame, use
transform("size")(ortransform("count")) so you get one value per original row. The plainsize()result has one row per group and will not line up.
df["rows_in_plan"] = df.groupby("plan")["city"].transform("size")
# 0 3, 1 4, 2 3, 3 4, 4 4, 5 4, 6 3Summary
Use size for the number of rows, count for the number of filled values in a column, and nunique for the number of different values in a column. Compare them in one agg call when you suspect missing or repeated data. Check how missing group keys are handled with dropna.
Exercise
Using the DataFrame in this chapter, what do df.groupby("plan")["city"].size(), df.groupby("plan")["city"].count() and df.groupby("plan")["city"].nunique() return for the "free" group, and why do the three numbers differ?
Show answer
They return 3, 2 and 1. The "free" group has three rows (Oslo, Oslo, and a missing city), so size returns 3. count skips the missing city and returns 2. nunique skips the missing city and counts Oslo once, so it returns 1.
Exercise
Write code that gives the number of rows for every city, including the row with the missing city, so the sizes add up to len(df).
Show answer
df.groupby("city", dropna=False).size() returns Oslo 3, Paris 1, Rome 2 and NaN 1. These add up to 7. Without dropna=False the row with the missing city is dropped from the groups, and the total is 6.