Sub topic 15
Counting numeric data in bins
This chapter assumes you can create a pandas Series, you know that value_counts counts each distinct value, and you know that missing values are skipped by default.
Why bin numeric data
value_counts treats every distinct value as its own category. That works for cities or plans. For a numeric column such as age or price, it usually produces one row per value, each with a count of 1 or 2. Binning groups the numbers into ranges first, so you count how many values fall in each range.
Equal-width bins with `bins=`
Pass an integer to bins and pandas splits the range from the minimum to the maximum into that many equal-width intervals.
import pandas as pd
ages = pd.Series([5, 12, 17, 18, 25, 33, 41, 58, 64, 70])
by_width = ages.value_counts(bins=3)
print(by_width)
in_order = ages.value_counts(bins=3, sort=False)
print(in_order)The index of the result is made of intervals. Each interval is open on the left and closed on the right, so (26.667, 48.333] excludes 26.667 and includes 48.333. The first lower edge is nudged slightly below the minimum so the smallest value is included. The counts here are 5, 2 and 3. By default the result is sorted by count, so the busiest bin comes first. Use sort=False or .sort_index() to see the bins in numeric order.
Your own edges with `pd.cut`
Equal-width bins rarely match real categories. pd.cut lets you choose the edges and name the bins. Calling value_counts on its result counts them.
import pandas as pd
ages = pd.Series([5, 12, 17, 18, 25, 33, 41, 58, 64, 70])
groups = pd.cut(
ages,
bins=[0, 17, 34, 64, 120],
labels=["under 18", "18-34", "35-64", "65+"],
)
print(groups.value_counts(sort=False))
print(groups.value_counts(sort=False, normalize=True))The counts are 3, 3, 3 and 1. The second call returns the same bins as fractions, because normalize works as it does for any Series.
Edge cases to check
- Values outside the edges. A value that falls outside every bin becomes
NaNin thepd.cutresult.value_countsthen skips it, so the counts add up to less than the length of the Series. Comparegroups.isna().sum()with zero to catch this. - Empty bins.
pd.cutproduces a categorical column, so a bin with no values still appears with a count of 0. This is useful for reports with a fixed layout. - Boundary values. Intervals are right-closed by default, so 17 lands in "under 18" and 18 lands in "18-34". Pass
right=Falseto make them left-closed instead. - Sort order. Use
sort=Falseon the cut result to keep the bins in the order you defined them.
Exercise
Given scores = pd.Series([40, 55, 62, 70, 85, 91, 100]), write code that counts how many scores fall in the bins 0-59, 60-79 and 80-100, labelled "fail", "pass" and "high", in that order. Note that pd.cut bins are right-closed by default. What are the three counts?
Show answer
Use pd.cut(scores, bins=[-1, 59, 79, 100], labels=["fail", "pass", "high"]).value_counts(sort=False). The lowest edge is -1 so that 0 would be included. The counts are fail 2 (40 and 55), pass 2 (62 and 70) and high 3 (85, 91 and 100).