Sub topic 15
Counting Numeric Data in Bins
This chapter assumes you know value_counts, how missing values behave in counts, and how to select a column from a DataFrame. Those are covered in earlier chapters.
Why bin numeric data
value_counts works well when a column has a few repeated values, such as cities or plans. A numeric column like age, price, or response time usually has many distinct values, so every count is 1 or 2 and the result tells you little. Binning groups the numbers into intervals first. You then count how many values fall in each interval, which gives a histogram in table form.
pandas offers three ways to do this:
value_counts(bins=...)bins and counts in one call.pd.cutmakes bins you define, so you can control edges and labels.pd.qcutmakes bins that each hold about the same number of values.
Setup used in the examples
The code blocks in this chapter continue from this one.
import numpy as np
import pandas as pd
ages = pd.Series([3, 17, 18, 22, 25, 31, 38, 45, 52, 64, 70, np.nan])The Series has 12 entries and 11 non-missing values. The missing value matters in several examples below.
Binning inside value_counts
Pass an integer to bins and pandas splits the range from the minimum to the maximum into that many equal-width intervals.
equal_width = ages.value_counts(bins=3, sort=False)
print(equal_width)The minimum is 3 and the maximum is 70, so each interval is about 22.3 wide. The counts are 5, 3, and 3. pandas widens the lowest edge slightly (by 0.1% of the range) so the minimum value lands inside the first bin. The result is indexed by Interval objects. With sort=False the bins stay in numeric order. The default sort=True orders them by count, which scrambles the scale and is rarely what you want for a histogram.
Pass a list to bins for your own edges.
edges = [0, 18, 35, 65, 100]
by_edges = ages.value_counts(bins=edges, sort=False)
print(by_edges)
print(by_edges.sum()) # 11The counts are 3, 3, 4, and 1. The sum is 11, not 12, because value_counts drops the missing value. This matches its behavior on non-numeric data. normalize=True also works with bins and returns fractions of the 11 counted values.
Interval edges: which side is closed
The notation (18, 35] means the interval excludes 18 and includes 35. By default, intervals are closed on the right. This decides where a value that sits exactly on an edge is counted. In the data above, the age 18 falls in (0, 18].
With pd.cut you can flip the convention using right=False.
right_closed = pd.cut(ages, bins=edges) # (0, 18], (18, 35], ...
left_closed = pd.cut(ages, bins=edges, right=False) # [0, 18), [18, 35), ...
print(right_closed.value_counts(sort=False)) # 3, 3, 4, 1
print(left_closed.value_counts(sort=False)) # 2, 4, 4, 1The age 18 moves from the first bin to the second, so the counts change from 3, 3, 4, 1 to 2, 4, 4, 1. Pick the convention that matches how your categories are defined. "Under 18" means right=False. "Up to and including 18" means the default.
Labels and the out-of-range trap
pd.cut accepts labels, which replaces the interval notation with readable names. The number of labels must equal the number of bins.
labels = ["child", "young adult", "adult", "senior"]
groups = pd.cut(ages, bins=edges, labels=labels)
print(groups.value_counts(sort=False))
print(groups.value_counts(sort=False, dropna=False))The result is a categorical Series. The second call adds a row for the missing age, with a count of 1. Without dropna=False you cannot tell from the output that a row was lost.
Values outside the edges also become missing. This is the most common mistake with explicit bins.
check = pd.cut(pd.Series([5, 120]), bins=edges)
print(check.isna().sum()) # 1, because 120 is above the last edgeA reliable habit is to compare the total with the number of values you expected to count.
binned = pd.cut(ages, bins=edges)
lost = ages.notna().sum() - binned.notna().sum()
print(lost) # 0 means every non-missing age landed in a binIf lost is not zero, your edges do not cover the data.
Equal-count bins with qcut
Equal-width bins can be very uneven when the data is skewed. Most incomes may fall in the first bin, with a few huge values stretching the range. pd.qcut places edges at quantiles so each bin holds roughly the same number of values.
quartiles = pd.qcut(ages, q=4)
print(quartiles.value_counts(sort=False)) # 3, 3, 2, 3The 11 non-missing values cannot split evenly into four groups, so one bin gets 2. The edges are 3 (lowest, included), 20, 31, 48.5, and 70. They come from the data, which means they are not round numbers. You can pass your own quantiles instead, such as q=[0, 0.5, 0.9, 1].
If many values repeat, two quantile edges can be identical and qcut raises a ValueError. Pass duplicates="drop" to merge the duplicate edges, and expect fewer bins than you asked for.
Empty bins
A categorical result keeps bins that contain no values, and reports them with a count of 0. This is useful, because a gap in the data stays visible.
sparse = pd.cut(pd.Series([5, 10, 70]), bins=edges)
print(sparse.value_counts(sort=False)) # 2, 0, 0, 1When you group by a binned column, groupby may or may not include the empty bins depending on the observed argument. Set it explicitly to avoid surprises and version warnings.
df = pd.DataFrame({"age": ages, "plan": ["free", "pro"] * 6})
df["age_group"] = pd.cut(df["age"], bins=edges, labels=labels)
per_group = df.groupby("age_group", observed=False).size()
print(per_group) # 3, 3, 4, 1size counts rows, so the row with a missing age is not placed in any group, because a missing group key is dropped by groupby. The four counts add up to 11 even though the DataFrame has 12 rows.
Choosing a method
| Method | Bin edges | Typical use | Watch for |
|---|---|---|---|
| `value_counts(bins=n)` | Equal width, from the data range | Quick look at a distribution | Default sort by count hides the order of bins |
| `value_counts(bins=list)` | Your edges | Quick count with known edges | Missing values are dropped |
| `pd.cut` | Your edges or an integer | Named groups, reusable column | Values outside edges become missing |
| `pd.qcut` | Quantiles of the data | Skewed data, ranking groups | Repeated values can create duplicate edges |
Edge cases to remember
- Integer
binsdepends on the data. If a new batch has a different minimum or maximum, the edges shift and the counts are no longer comparable. Use explicit edges when you compare datasets. sort=Trueis the default invalue_counts, but binned output is almost always better withsort=Falseor followed bysort_index().- Infinite values work as outer edges.
bins=[-np.inf, 18, 65, np.inf]guarantees that no finite value falls outside the bins. - A column that looks numeric but has the
objectdtype, for example numbers read as text, fails inpd.cut. Convert it first withpd.to_numeric.
Exercise
A Series s = pd.Series([0, 5, 10, 10, 20, np.nan]) is counted with pd.cut(s, bins=[0, 10, 20]). How many values land in bins, how many become missing, and which single argument change makes the 0 count?
Show answer
The intervals are (0, 10] and (10, 20]. The values 5, 10, 10, and 20 land in bins (3 in the first, 1 in the second). The 0 is excluded because the lowest edge is open, and the original NaN stays missing, so 2 entries are missing. Adding include_lowest=True puts the 0 in the first bin, giving 4 values in the first bin and 1 in the second.
Exercise
Why can ages.value_counts(bins=edges).sum() be smaller than len(ages), and how do you see how many entries were lost?
Show answer
value_counts drops missing values, and any value outside the edges is not counted either. Compare ages.notna().sum() with the sum of the counts to find values that fell outside the edges. Use pd.cut(ages, bins=edges).value_counts(dropna=False) to see the missing entries as their own row.