Sub topic 1
Binning Numeric Data with `cut` and `qcut` in pandas
Prerequisites
This chapter assumes basic Python, pandas Series and DataFrame use, and descriptive statistics such as minimum, maximum, and percentiles.
Why and when to bin numeric data
Binning converts numeric values into a small set of ranges, called bins. This helps when exact values are too detailed for a report, chart, or comparison. For example, ages can become child, adult, and senior groups.
Binning is useful for:
- Summarizing measurements by range.
- Creating readable chart categories.
- Applying different rules to value bands.
- Comparing groups without focusing on small numeric differences.
Binning also loses detail. Choose meaningful boundaries, and keep the original numeric column when later analysis needs exact values.
Equal-width bins with `pd.cut`
pd.cut assigns values to intervals. When bins is an integer, pandas divides the range from the minimum to the maximum into that many equal-width intervals.
import pandas as pd
ages = pd.Series([3, 17, 25, 42, 67, 90])
age_groups = pd.cut(ages, bins=3)
print(age_groups)The result is a categorical Series. Each value belongs to one interval category. Equal-width bins are useful when the numeric scale has meaningful, consistent distances. They may produce groups with very different numbers of rows if the data is unevenly distributed.
Choosing your own bin edges
Pass a list of edges when domain rules define the ranges. The list [0, 18, 65, 120] creates three intervals.
bins = [0, 18, 65, 120]
labels = ["child", "adult", "senior"]
groups = pd.cut(ages, bins=bins, labels=labels)
print(groups)Explicit edges make the analysis easier to explain and reproduce. Every input should fit between the first and last edge. Values outside that range become NaN, which represents a missing value.
Which side is closed: `right` and `include_lowest`
By default, intervals are closed on the right. With edges [0, 10, 20], the bins are (0, 10] and (10, 20]. The right edge is included, but the left edge is excluded.
Use include_lowest=True to include the lowest value in the first bin. Use right=False for left-closed intervals such as [0, 10) and [10, 20).
values = pd.Series([0, 10, 20])
print(pd.cut(values, bins=[0, 10, 20], include_lowest=True))
print(pd.cut(values, bins=[0, 10, 20], right=False))Exercise
Which option creates left-closed intervals, including the left edge but excluding the right edge?
Show answer
Use pd.cut(values, bins=[0, 10, 20], right=False).