Sub topic 5
Counting rows: size versus count
This chapter assumes you can build a DataFrame, select columns, and read a Series with an index. You should also know the basic groupby(...)[col].sum() form from the earlier chapters. Here you will learn two methods that look alike but answer different questions: size and count.
Two questions that sound the same
"How many rows are in each group?" and "How many values are in each group?" have the same answer only when no data is missing. Pandas gives them separate methods:
sizecounts rows in each group, whatever their values are.countcounts non-missing values, separately for each column.
Missing values are NaN, None, or NaT for datetimes. size ignores them. count skips them.
Seeing the difference
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 returns 2. One of those rows has a missing v, so count returns 1. Group b has no missing values, so both methods return 1.
The two results also differ in their metadata. size returns an unnamed Series, because no column was involved. count returns a Series named after the column you counted.
How each method works
size needs no column values. Pandas already knows how many rows it assigned to each group when it did the split, so it reports that number. Because size never reads cell values, it cannot be affected by missing data in non-key columns.
count checks every value in the selected column or columns and tallies the ones that are not missing. The result depends on your data.
| Property | `size` | `count` |
|---|---|---|
| What it counts | Rows in the group | Non-missing values |
| Affected by `NaN` in value columns | No | Yes |
| Return type on a DataFrameGroupBy | Series | DataFrame, one column per input column |
| Return type on a column selection | Series | Series |
| Can differ between columns | No | Yes |
What counts as missing
count treats NaN, None, and NaT as missing. Other values that look empty are not missing. These all count as present:
- an empty string
"" - the number
0 - the string
"NaN"
If your data uses an empty string for "no value", count will include it. Convert such values to real missing values first, for example with replace("", pd.NA).
Counting on a whole DataFrame
If you call count without selecting a column, you get one count per remaining column. The grouping key is left out of the result, because it is already the index.
import pandas as pd
data = pd.DataFrame({
"k": ["a", "a", "b", "b"],
"v": [1.0, None, 3.0, 4.0],
"w": [None, None, 5.0, None],
})
print(data.groupby("k").count())
# v w
# k
# a 1 0
# b 2 1
print(data.groupby("k").size())
# k
# a 2
# b 2
# dtype: int64This is the main reason count exists. Each column gets its own tally, so you can see how complete each one is per group. Group a has two rows but no usable w values at all. size gives a single number per group, and count gives a table of completeness.
Finding how much is missing
Because size counts every row and count counts the present values, their difference is the number of missing values in a column.
import pandas as pd
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [1.0, None, 3.0]})
g = data.groupby("k")
missing_v = g.size() - g["v"].count()
print(missing_v)
# k
# a 1
# b 0
# dtype: int64Pandas aligns the two Series on their index, which is the group key. The subtraction therefore pairs each group with itself. This is a compact data-quality check. A group with a large gap between size and count deserves a closer look before you trust its averages.
Getting a DataFrame instead of a Series
size returns a Series indexed by the group keys. If you want the keys as ordinary columns, pass as_index=False. Pandas then names the count column size.
import pandas as pd
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [1.0, None, 3.0]})
print(data.groupby("k", as_index=False).size())
# k size
# 0 a 2
# 1 b 1You can also call reset_index(name="n_rows") on the Series form if you want a different column name:
import pandas as pd
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [1.0, None, 3.0]})
counts = data.groupby("k").size().reset_index(name="n_rows")
print(counts)
# k n_rows
# 0 a 2
# 1 b 1The next chapters cover result shape in more detail. For now, remember that both forms hold the same numbers.
Using both inside agg
Named aggregation accepts "size" and "count" as function names. This puts both counts in one flat summary table.
import pandas as pd
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [1.0, None, 3.0]})
summary = data.groupby("k").agg(
n_rows=("v", "size"),
n_valid=("v", "count"),
mean_v=("v", "mean"),
)
print(summary)
# n_rows n_valid mean_v
# k
# a 2 1 1.0
# b 1 1 3.0Reading mean_v next to n_valid helps. Group a has a mean of 1.0, but that mean rests on a single value. The column n_rows would hide this fact by itself, so reporting both is good practice.
Missing group keys
Missing values in the key column behave differently from missing values in the value columns. By default, groupby drops rows whose key is missing. Those rows appear in neither size nor count.
import pandas as pd
keys = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
print(keys.groupby("k").size())
# k
# a 2
# dtype: int64
print(keys.groupby("k", dropna=False).size())
# k
# a 2
# NaN 1
# dtype: int64The default result sums to 2, while the DataFrame has 3 rows. A quick check is whether size().sum() equals len(df). If it does not, some rows were dropped because of missing keys. Passing dropna=False keeps them as a group of their own.
Choosing between them
The diagram summarizes the decision.
Use these rules in practice:
- Use
sizefor "how many records, orders, or events per group". It is faster and unaffected by missing values. - Use
countfor "how many measurements do I have per group". Use it before computing a mean, so you know how many values the mean is based on. - Use both together to measure missing data.
- Use
nuniqueinstead when you want the number of distinct values, not the number of values.
Related tools and edge cases
Series.value_counts()also counts rows per value, but it sorts the result by frequency, largest first.groupby(...).size()sorts by key by default. The numbers are the same, but the row order differs.- Categorical group keys can produce groups with zero rows. Whether
sizereports those zeros depends on theobservedparameter and your pandas version. A later chapter covers this. - Using
counton a column with no missing values gives the same numbers assize. Do not rely on this equality in code that might see messier data later. len(group)insideapplyor when iterating counts rows, likesize. Prefer the built-insizeto avoid a slow Python-level loop.
Exercises
Exercise
Given df = pd.DataFrame({"team": ["x", "x", "y", "y", "y"], "score": [1.0, None, None, None, 4.0]}), what do df.groupby("team").size() and df.groupby("team")["score"].count() return for each team, and how many scores are missing in each team?
Show answer
size gives x = 2 and y = 3, because team x has two rows and team y has three. count gives x = 1 and y = 1, because each team has exactly one non-missing score. Subtracting count from size gives one missing score for team x and two for team y.
Exercise
A DataFrame has 100 rows, but df.groupby("region").size().sum() returns 94. What is the most likely cause, and how do you make the group sizes sum to 100?
Show answer
Six rows have a missing value in the region column, and groupby drops rows with missing keys by default. Use df.groupby("region", dropna=False).size() so those rows form their own group, and the sizes then sum to 100.