Sub topic 5
Counting rows: size versus count
This chapter assumes you can build a DataFrame, select columns, and run a basic groupby(...).sum(). It covers the two ways to count rows per group and why they can disagree.
Two questions that sound alike
"How many rows are in each group?" and "How many values does each group have?" are different questions when data has gaps. pandas answers them with two different methods:
size()counts every row in the group, including rows with missing values.count()counts only the non-missing values in each column you ask about.
If your data has no missing values, the two agree. Once a NaN or None appears, they diverge.
A side-by-side example
import pandas as pd
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [1.0, None, 3.0]})
g = data.groupby("k")
print(g.size())
# k
# a 2
# b 1
# dtype: int64
print(g["v"].count())
# k
# a 1
# b 1
# Name: v, dtype: int64Group a has two rows, so size() reports 2. One of those rows has a missing v, so count() reports 1.
The outputs also differ in shape. size() returns a single Series, because it does not depend on any column. count() is a column-wise aggregation. Calling it on the whole GroupBy gives a DataFrame with one count per column, and selecting ["v"] first gives a Series.
print(g.count())
# v
# k
# a 1
# b 1How they work
The diagram shows where each method looks.
Choosing between them
| You want to know | Use |
|---|---|
| Number of rows per group | `size()` |
| Number of usable values in one column | `count()` on that column |
| Number of distinct values in a column | `nunique()` |
| Share of missing data per group | Compare `size()` with `count()` |
The last row is a handy check. Dividing count() by size() gives the fraction of values that are present in each group.
coverage = g["v"].count() / g.size()
print(coverage)
# k
# a 0.5
# b 1.0
# dtype: float64Common errors
- Using
count()to get group sizes. It works until a column has missing values, then silently under-reports. Usesize()when you mean rows. - Expecting
count()to return one column. Called on the whole GroupBy, it returns one column per non-key column, and each column can have a different count. - Confusing
count()withnunique().count()ignores duplicates, so[1, 1, 2]has a count of 3.nunique()returns 2.
Exercise
A DataFrame is grouped by "team". Team "x" has 4 rows, and the "score" column is missing in 1 of them. What do size() and g["score"].count() return for team "x"?
Show answer
size() returns 4, because it counts all rows. g["score"].count() returns 3, because it skips the missing score.
Exercise
Write an expression that returns, for each group in g, the fraction of rows where column "v" is missing.
Show answer
1 - g["v"].count() / g.size(). Equivalently, g["v"].apply(lambda s: s.isna().mean()).