Call df.groupby(["col1", "col2"], dropna=False).size().reset_index(name="count") (or df.value_counts(["col1", "col2"], dropna=False).reset_index()) to group a DataFrame by two columns and return a clean DataFrame containing each unique (col1, col2) pair along with its total row count—using .size() instead of .count() so rows with NaN values in non-grouping columns are not silently excluded.
Basic Example
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "North", None],
"status": ["paid", "paid", "pending", "paid", "failed", "paid"],
"amount": [100, 150, None, 200, 50, 75],
})
# 1. Recommended: `.groupby(...).size()` counts ALL rows per group (including NaN amounts)
grouped = (
df.groupby(["region", "status"], dropna=False)
.size()
.reset_index(name="row_count")
)
print(grouped)
# Output:
# region status row_count
# 0 North failed 1
# 1 North paid 2
# 2 South paid 1
# 3 South pending 1
# 4 NaN paid 1
# 2. Alternative (sorted automatically descending by frequency):
freq_sorted = df.value_counts(["region", "status"], dropna=False).reset_index()
print(freq_sorted)
# Output:
# region status count
# 0 North paid 2
# 1 North failed 1
# 2 South paid 1
# 3 South pending 1
# 4 NaN paid 1
Key Details & Edge Cases
.size()vs..count()— a critical Pandas trap:df.groupby(["col1", "col2"]).size()counts the total number of rows in each group (including rows where other columns containNaN/None), returning a singleSeriesof integers.df.groupby(["col1", "col2"]).count()counts non-null values separately in every remaining column, returning a DataFrame with repeated counts across all non-grouping columns and undercounting rows that haveNaNin those columns (or returning an empty DataFrame with 0 columns if there are no other columns besides"col1"and"col2"!).
- Include missing group keys with
dropna=False:- By default (
dropna=True), Pandas silently drops any group where"col1"or"col2"isNaN/None. Always passdropna=Falseif missing category combinations should appear in your counts.
- By default (
- Unused combinations on
Categoricalcolumns (observed=Truevs.observed=False):- If
"col1"or"col2"has apd.Categoricaldtype,observed=Falseincludes Cartesian combinations with0rows, whereasobserved=True(becoming the Pandas default) restricts output to(col1, col2)pairs actually present in the data.
- If
- Adding the group row count back onto every original row (
transform("size")):- When you want to keep the original DataFrame shape and attach each row’s
(col1, col2)group count as a new column (e.g., to filter groups withcount >= 2), use.transform("size"):df["group_count"] = df.groupby(["region", "status"], dropna=False)["status"].transform("size")
- When you want to keep the original DataFrame shape and attach each row’s
- Combining row counts with additional aggregations (
NamedAgg):- If you need row counts alongside sums or averages in one pass, use
.agg():summary = df.groupby(["region", "status"], dropna=False).agg( row_count=("status", "size"), total_amount=("amount", "sum"), ).reset_index()
- If you need row counts alongside sums or averages in one pass, use
Comparison of Two-Column Row-Counting Methods in Pandas
| Method | Counts Rows with NaN in Other Columns? |
Default Sort Order | Return Type | Best Used When |
|---|---|---|---|---|
df.groupby(["c1", "c2"], dropna=False).size().reset_index(name="count") (Recommended) |
Yes (counts every row in the group) | Sorted ascending by ("c1", "c2") keys |
pd.DataFrame (["c1", "c2", "count"]) |
Standard SQL-style GROUP BY c1, c2 row counts in clean tabular form. |
df.value_counts(["c1", "c2"], dropna=False).reset_index() |
Yes (counts every row in the pair) | Sorted descending by count |
pd.DataFrame (["c1", "c2", "count"]) |
Finding the most frequent two-column combinations immediately without an extra .sort_values(). |
df.groupby(["c1", "c2"]).agg(count=("c1", "size")) |
Yes | Sorted ascending by ("c1", "c2") keys |
pd.DataFrame |
Computing row counts alongside sums, means, or min/max metrics in a single .groupby() call. |
df.groupby(["c1", "c2"]).count() (Avoid for row counts) |
No (ignores NaN per column) |
Sorted ascending by ("c1", "c2") keys |
pd.DataFrame (all non-key columns) |
Counting non-missing entries individually for each non-grouped column. |
You must log in or register to comment.
