Sub topic 1
Why and when to bin numeric data
Prerequisites
This chapter assumes you can:
- Write basic Python, including lists and function calls with keyword arguments.
- Create and index a pandas Series and DataFrame.
- Read simple descriptive statistics such as minimum, maximum, and percentiles.
What binning is
Binning, also called discretization, converts a continuous numeric column into a small set of ranges. Each value is replaced by the range it falls into. An age of 42 becomes "adult", and a price of 18 becomes "low".
pandas has two main functions for this:
pd.cutsplits values using edges that you choose, or edges of equal width.pd.qcutsplits values at quantiles, so each bin holds a similar number of rows.
The later chapters cover both in detail. This chapter explains when binning is worth doing.
Why bin
Binning is useful in these cases:
- Reporting. A table with "under 18", "18 to 65", and "over 65" is easier to read than a table of exact ages.
- Business rules. Tax brackets, shipping tiers, and age restrictions are already defined as ranges.
- Grouping. Once a column is binned, you can use it as a
groupbykey and compare the groups. - Reducing noise. Exact values can be unreliable, such as self-reported income. A coarse band can be more trustworthy than the exact figure.
- Feature engineering. Some models handle a few categories better than a raw number, especially when the relationship with the target is not a straight line.
A first example
This example turns six ages into three groups and counts how many fall in each.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
groups = pd.cut(ages, bins=[0, 18, 65, 120], labels=["child", "adult", "senior"])
print(groups.value_counts().sort_index())The result is a categorical Series. Each age is replaced by one of three labels, and each label contains two of the six ages. By default each range includes its right edge, so 18 would count as "child" and 65 as "adult".
What you give up
Binning discards information, so use it with care.
- Two values at opposite ends of a bin become identical. Ages 19 and 64 are both "adult".
- Two values on either side of an edge become different. Ages 65 and 66 land in separate bins, even though they are nearly the same.
- The edges you choose affect the results, and small changes to them can change a summary noticeably.
- Values outside the edges become
NaN, so a badly chosen range silently loses rows.
Do not bin if the analysis can use the exact numbers. Means, correlations, and regressions on the raw column are usually more precise than the same calculations on bins.
Deciding whether to bin
Common mistakes
- Binning too early. Keep the original column and add the binned one next to it. You can then change the edges later without reloading the data.
- Picking edges without looking at the data. Check the minimum and maximum first so no values fall outside the outer edges.
- Using too many bins. Many narrow bins bring back the noise you wanted to remove. Use few enough bins that each one holds a useful number of rows.
- Treating labels as numbers. The result is categorical, so you cannot average it.
Exercise
A dataset has household incomes from 12,000 to 450,000, and the legal tax brackets have fixed boundaries. Should you use pd.cut or pd.qcut to assign each household to a bracket, and why?
Show answer
Use pd.cut with the bracket boundaries as explicit edges. The brackets are defined by fixed values, not by how many households fall in each one. pd.qcut would place edges at quantiles of this particular dataset, so they would not match the legal boundaries.
Exercise
Name two ways that binning a column can make an analysis worse.
Show answer
It discards detail, because values at opposite ends of a bin become identical. It can also separate nearly equal values that sit on either side of an edge. Values outside the outer edges also become NaN, so rows can be lost silently.