Binning and Discretization
Why bin values?
Section titled “Why bin values?”Binning (discretization) converts numeric values into categories:
- Age → {0–18, 19–35, 36–60, 60+}
- Spend → {low, medium, high}Use cases:
- Easier reporting and segmentation
- Non-linear relationship capture (sometimes)
- Feature engineering
pd.cut (fixed bins)
Section titled “pd.cut (fixed bins)”import pandas as pd
age = pd.Series([12, 19, 25, 38, 52, 67])
bins = [0, 18, 35, 60, 200]
labels = ["0-18", "19-35", "36-60", "60+"]
age_group = pd.cut(age, bins=bins, labels=labels, right=True, include_lowest=True)
print(age_group)pd.qcut (quantile bins)
Section titled “pd.qcut (quantile bins)”Quantile binning tries to put roughly equal number of rows in each bin.
import pandas as pd
values = pd.Series([10, 15, 20, 25, 30, 40, 60, 100])
bucket = pd.qcut(values, q=3, labels=["low", "mid", "high"])
print(bucket)- Choose bins based on domain meaning.
- Quantile bins are useful when distributions are skewed.
- Always check counts per bin after binning.
Visualize it
Section titled “Visualize it” flowchart LR
A["Continuous values"] --> B{"cut or qcut?"}
B -->|"fixed edges"| C["pd.cut(values, bins)"]
B -->|"equal-sized groups"| D["pd.qcut(values, q)"]
C --> E["Category per row"]
D --> E
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Bin with fixed edges
Section titled “Exercise 1 – Bin with fixed edges”Exercise 2 – Bin into equal-sized quantile groups
Section titled “Exercise 2 – Bin into equal-sized quantile groups”Exercise 3 – Count rows per bin
Section titled “Exercise 3 – Count rows per bin”Bins turn numbers into categories — pair this with Train-Test Split Concepts before you build and evaluate a model on them.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading