Sub topic 13
Summarizing by bin with value_counts and groupby
This chapter assumes you can create a pandas Series and DataFrame, and that you know pd.cut and pd.qcut return a categorical result. Binning is rarely the last step. You usually bin a column so you can count or aggregate rows by band.
Counting rows with value_counts
value_counts() on a binned Series reports how many values fall in each bin.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90, 30, 55])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.value_counts())
print(groups.value_counts(sort=False))By default the result is sorted by count, largest first. That order is rarely what you want for ranges. With sort=False, the bins appear in their natural order: child, adult, senior. Calling .sort_index() on the default result has the same effect.
For a categorical, value_counts() also lists categories with zero rows. A zero is real information. It tells you a bin exists but nothing landed in it.
Two options help with reports:
normalize=Truereturns proportions instead of counts.dropna=Falseadds a row for NaN, which shows how many values fell outside the bins or were missing.
Aggregating with groupby
Because the bin column is categorical, you can pass it to groupby like any other key. This lets you summarize a different column, or several, for each bin.
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.groupby("price_band", observed=True)["price"].agg(["count", "mean"]))The output has one row per band. low holds 5, 12 and 18, so its count is 3 and its mean is about 11.67. mid holds 2 rows with a mean of 32.5. high holds 3 rows with a mean of about 73.33.
The observed parameter
observed controls what happens to categories with no rows.
observed=Falseincludes every category. Empty bins show a count of 0 and NaN for the mean.observed=Trueincludes only bins that occur in the data.
The default has changed across pandas versions, and some versions warn when you leave it unset. Pass observed explicitly so your code behaves the same everywhere. Choose False when you want a fixed set of rows, such as a report where every band must appear. Choose True when empty bands are noise.
Common errors
- Reading the default
value_counts()order as the bin order. Usesort=Falseorsort_index(). - Missing rows in a groupby result because the bins have NaN.
groupbydrops NaN keys by default, so rows outside the bins vanish from the summary. Checkdf["price_band"].isna().sum()first. - Different group counts between
observed=Trueandobserved=False. The data is the same. Only the empty bins differ.
Exercise
A DataFrame has a numeric column "score". You run df["band"] = pd.cut(df["score"], bins=[0, 50, 100], labels=["low", "high"]), then df.groupby("band", observed=True)["score"].count().sum(). The result is smaller than len(df). What are two likely causes, and how can you find out which applies?
Show answer
Some scores are NaN, or they fall outside the bins. With right-closed intervals, a score of exactly 0 is outside (0, 50], and scores above 100 are also excluded. Both cases give a NaN band, and groupby drops those rows. Check df["band"].isna().sum() or df["band"].valuecounts(dropna=False). Then compare df["score"].isna().sum() to see how many NaNs came from missing input. The rest fell outside the bins, which you can fix with includelowest=True or wider edges.