Sub topic 13
Summarizing by bin with value_counts and groupby
Binning only pays off when you summarize the result. This chapter shows how to count rows per bin with value_counts, and how to compute statistics per bin with groupby. It also covers the settings that decide whether empty or missing bins show up.
It assumes you can build a binned column with pd.cut or pd.qcut, and that you know the basics of Series, DataFrame and groupby. If you need to review bin edges, closure and labels, see the earlier chapters.
Why binned columns summarize well
pd.cut and pd.qcut return a categorical Series. A categorical column has a fixed list of categories, and that list stays attached to the column even when some categories have no rows. In bin-based reports this matters in three ways:
- The bins keep their natural order (low, mid, high), not alphabetical order.
- Empty bins can stay in the output as zeros, so a gap in your data stays visible.
- The binned column works as a
groupbykey without any conversion.
Counting rows per bin with value_counts
Series.value_counts() counts how many rows fall in each bin. This reuses the price example from earlier in the tutorial.
import pandas as pd
df = pd.DataFrame({"price": [5, 12, 18, 25, 40, 55, 70, 95]})
bins = [0, 20, 50, 100]
df["price_band"] = pd.cut(df["price"], bins=bins, labels=["low", "mid", "high"])
print(df["price_band"].value_counts())Three prices fall in low (5, 12, 18), two in mid (25, 40) and three in high (55, 70, 95). By default value_counts sorts by count, largest first. Ties keep no guaranteed order. For bins you almost always want bin order instead. You have two options:
import pandas as pd
df = pd.DataFrame({"price": [5, 12, 18, 25, 40, 55, 70, 95]})
df["price_band"] = pd.cut(
df["price"], bins=[0, 20, 50, 100], labels=["low", "mid", "high"]
)
# Option 1: skip the count sort
print(df["price_band"].value_counts(sort=False))
# Option 2: sort by the categorical order of the index
print(df["price_band"].value_counts().sort_index())sort_index() is the more explicit choice. It gives bin order no matter how the counts compare.
Proportions instead of counts
Pass normalize=True to get the share of rows in each bin. The shares add up to 1.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90, 35, 29])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.value_counts(normalize=True).sort_index().round(3))The denominator is the number of rows that landed in a bin. Rows that became NaN are left out of it unless you pass dropna=False. The sections on missing values below explain why this matters.
Empty bins appear as zeros
For a categorical Series, value_counts lists every category, including those with no rows.
import pandas as pd
ages = pd.Series([3, 17, 25, 42])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.value_counts().sort_index())No age is above 65, so senior appears with a count of 0. This behavior is useful. A report with a fixed set of bands keeps the same rows from run to run, even when one band has no data in a given month.
Statistics per bin with groupby
value_counts only counts. To compute a mean, sum or any other statistic, use the binned column as a groupby key. This example uses a second column, spend, to summarize by age band.
import pandas as pd
df = pd.DataFrame({
"age": [22, 25, 31, 38, 44, 52, 58, 63, 71],
"spend": [120, 90, 200, 150, 310, 280, 240, 180, 60],
})
df["age_band"] = pd.cut(
df["age"],
bins=[20, 35, 50, 65, 80],
labels=["21-35", "36-50", "51-65", "66-80"],
)
summary = df.groupby("age_band", observed=True).agg(
customers=("spend", "size"),
total=("spend", "sum"),
average=("spend", "mean"),
)
print(summary)The 21-35 band holds three customers whose mean spend is about 136.67. The 36-50 band holds two with a mean of 230. The 51-65 band holds three with about 233.33, and the 66-80 band holds one with a mean of 60.
The agg call uses named aggregation. Each keyword becomes an output column, and each value is a (column, function) pair. size counts rows, including rows where spend is missing. count counts only non-missing values. The difference matters when the measured column has gaps.
To turn the result into a flat table, call reset_index():
flat = summary.reset_index()
print(flat)The age_band column stays categorical after reset_index(), so it keeps its order and its category list.
The observed parameter
When you group by a categorical column, observed decides what happens to categories that have no rows:
| Setting | Behavior | Result for an empty bin |
|---|---|---|
| `observed=True` | Only categories present in the data become groups | The bin is absent |
| `observed=False` | Every category becomes a group | The bin appears with count 0 and NaN for means |
Here is the difference on data with an empty bin.
import pandas as pd
df = pd.DataFrame({"age": [3, 17, 25, 42], "spend": [10, 15, 80, 95]})
df["group"] = pd.cut(
df["age"], bins=[0, 18, 65, 120], labels=["child", "adult", "senior"]
)
print(df.groupby("group", observed=False)["spend"].agg(["count", "mean"]))
print(df.groupby("group", observed=True)["spend"].agg(["count", "mean"]))The first call lists senior with a count of 0 and a mean of NaN. The second call has only child and adult.
Choose observed=False when the report must always show every band, for example a fixed dashboard. Choose observed=True when empty bands would only add noise. Be careful with observed=False and a sum. An empty bin gives a sum of 0, but a mean, minimum or maximum of NaN. Downstream code that does arithmetic on those columns needs to expect that.
Missing values and out-of-range values
A row becomes NaN in the binned column for two reasons. Its value may fall outside every bin, or the input may already be missing. Both kinds of rows are dropped from groupby results by default, and value_counts skips them too. Totals can then look smaller than your row count without any error.
import pandas as pd
s = pd.Series([5, 12, 150, None, 40])
band = pd.cut(s, bins=[0, 20, 50, 100], labels=["low", "mid", "high"])
print(band.value_counts().sum()) # rows that landed in a bin
print(band.value_counts(dropna=False)) # includes a NaN row
print(band.isna().sum()) # rows in no binHere 150 is above the last edge and None was missing from the start, so two of the five rows are NaN. The first print shows 3 and the last shows 2. A good habit is to compare the sum of the bin counts with len(s) before you trust a summary. If they differ, band.isna() tells you which rows were excluded. Then either widen the bin edges for the out-of-range rows or deal with the missing input separately.
To keep NaN rows visible in a grouped result, pass dropna=False to value_counts. With groupby, dropna=False works as well in current pandas versions, and it adds a group for the missing key.
Summaries over quantile bins
The same tools work on pd.qcut output. The difference is in how you read the result. Quantile bins have about equal counts by design, so the counts are rarely the interesting part. The statistics of another column are.
import pandas as pd
df = pd.DataFrame({
"age": [22, 25, 31, 38, 44, 52, 58, 63, 71],
"spend": [120, 90, 200, 150, 310, 280, 240, 180, 60],
})
df["spend_tier"] = pd.qcut(
df["spend"], q=3, labels=["bottom", "middle", "top"]
)
print(df["spend_tier"].value_counts().sort_index())
print(df.groupby("spend_tier", observed=True)["age"].agg(["min", "mean", "max"]))There are nine rows and three tiers, so each tier has three rows. The groupby then answers a different question: how old are the customers in the bottom, middle and top spending tiers? This is a common pattern. You bin one column by rank and look at what another column does across the bins.
When qcut drops duplicate edges with duplicates="drop", you get fewer bins than you asked for. If you also passed labels, the number of labels must match the number of bins that remain. A mismatch raises an error. Check the edges with retbins=True before you write the labels.
Common errors
- Counts in the wrong order.
value_counts()sorts by size. Add.sort_index()orsort=False. - A band is missing from the output. You used
observed=True, and the band has no rows. Switch toobserved=Falseif you need it. - Counts do not add up to the row count. Rows are NaN because they are out of range or missing. Use
dropna=Falseor checkisna().sum(). - NaN means in a table. Those are empty bins under
observed=False. Fill them withfillnaonly if a placeholder makes sense for your report. - Grouping by the original numeric column. If you group by
priceinstead ofprice_band, you get one group per distinct value. Check the key.
Exercise
A DataFrame df has a column score with 200 rows. You run df["band"] = pd.cut(df["score"], bins=[0, 50, 100], labels=["low", "high"]). Then df["band"].value_counts().sum() returns 188. What are two possible causes for the missing 12 rows, and how would you find out which applies?
Show answer
Each of the 12 rows is NaN in band, either because score is outside the edges or because score was already missing. A score of exactly 0 is one case, since the default right=True makes the first interval (0, 50] and excludes 0. Scores below 0 or above 100 are another. Run df["band"].isna().sum() to confirm that 12 rows are NaN. Then check df.loc[df["band"].isna(), "score"].isna().sum() for how many have a missing score, and df.loc[df["band"].isna(), "score"].describe() for the out-of-range values. If 0 is the problem, add include_lowest=True. Otherwise widen the edges.
Exercise
You group a binned column with df.groupby("band", observed=False)["spend"].agg(["count", "mean"]). One band has no rows. What do the count and mean columns show for that band, and what happens if you change to observed=True?
Show answer
With observed=False the empty band appears with a count of 0 and a mean of NaN. With observed=True the band is left out of the result entirely.