Sub topic 2
Counting Rows and Shaping Grouped Results
Assume you know basic Python, pandas DataFrame and Series objects, and pandas indexes. A GroupBy object represents rows split into groups. Aggregation then calculates one result per group.
Counting rows: `size` versus `count`
size() counts every row in each group. count() counts only non-missing values in the selected column.
| Method | What it counts | Missing values |
|---|---|---|
| `size()` | Rows in each group | Included |
| `count()` | Non-null values in a column | Excluded |
import pandas as pd
data = pd.DataFrame({
"region": ["North", "North", "South"],
"revenue": [100.0, None, 80.0],
})
groups = data.groupby("region")
print(groups.size())
# region
# North 2
# South 1
print(groups["revenue"].count())
# region
# North 1
# South 1Use size when you need row counts. Use count when you need the number of available values in a particular column.
Several aggregations with `agg`
agg applies multiple calculations in one operation. Named aggregation gives each output column a clear name.
summary = (
data.groupby("region")
.agg(
total_revenue=("revenue", "sum"),
average_revenue=("revenue", "mean"),
row_count=("region", "size"),
)
)
print(summary)Each named aggregation has the form output_name=("input_column", "function").
Shaping the result
By default, grouping columns become the result index. Use as_index=False to keep them as ordinary columns, or call reset_index() afterward.
summary = (
data.groupby("region", as_index=False)
.agg(total_revenue=("revenue", "sum"))
)
summary = data.groupby("region")["revenue"].sum().reset_index()These approaches produce a regular column named region, which is often easier to merge, export, or plot.
> callout note > as_index=False affects the result of the current grouping operation. It does not change the original DataFrame index.
Missing keys and group ordering
Rows with missing grouping keys are excluded by default. Pass dropna=False to keep missing keys as a group. By default, pandas sorts group keys. Pass sort=False to retain their first-seen order.
keys = pd.DataFrame({
"region": ["South", None, "North", "South"],
"units": [4, 2, 7, 3],
})
result = (
keys.groupby("region", dropna=False, sort=False)
.agg(total_units=("units", "sum"))
.reset_index()
)
print(result)Use dropna=False when an unknown key has analytical meaning. Check ordering explicitly before comparing results or presenting them.
Exercise
Which method counts two rows when one row has a missing value in the selected column: size or count?
Show answer
size counts both rows; count counts only the non-missing value.