Sub topic 3
Custom Quantile Cut Points with pandas
Assume you know how to create pandas Series and DataFrames and understand percentiles. Use pd.qcut when boundaries should come from the data distribution rather than fixed numeric widths.
Custom quantile cut points
Pass a list of fractions between 0 and 1 to q. For example, [0, 0.5, 0.9, 1] creates a lower half, a middle band, and a top 10% band.
import pandas as pd
scores = pd.Series([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
bands, edges = pd.qcut(
scores,
q=[0, 0.5, 0.9, 1],
labels=["lower", "middle", "top"],
retbins=True,
)
print(bands)
print(edges)qcut calculates the numeric edges from quantiles. The bins may have different widths, but they target the requested proportions of rows.
Repeated values and duplicate edges
Repeated values can make two quantiles equal. In that case, qcut cannot create a nonempty interval between those edges and raises a ValueError. Use duplicates="drop" to remove repeated edges.
values = pd.Series([1, 1, 1, 1, 1, 2, 3, 4])
groups, edges = pd.qcut(
values,
q=4,
duplicates="drop",
retbins=True,
)
print(groups)
print(edges)With dropped edges, fewer bins may exist than the requested number. Check the returned edges and categories instead of assuming the original count.
Inspecting edges with `retbins`
Set retbins=True to receive a tuple: the binned result and the numeric edge array. Save these edges when you need to apply the same boundaries to another dataset.
Choosing and summarizing bins
Use cut for fixed business ranges, such as prices from 0–20 and 20–50. Use qcut for rank-based groups, such as quartiles or a custom top 10% group.
A binned Series is categorical, so it works directly with value_counts and groupby.
import pandas as pd
df = pd.DataFrame({"price": [5, 12, 18, 25, 40, 55, 70, 95]})
edges = [0, 20, 50, 100]
df["band"] = pd.cut(df["price"], bins=edges, labels=["low", "mid", "high"])
print(df["band"].value_counts().sort_index())
print(df.groupby("band", observed=True)["price"].agg(["count", "mean"]))Reusing bins with an `IntervalIndex`
An IntervalIndex stores intervals explicitly and can be passed as bins. This is useful when several columns or datasets must use identical ranges.
intervals = pd.IntervalIndex.from_tuples([(0, 20), (20, 50), (50, 100)])
df["interval_band"] = pd.cut(df["price"], bins=intervals)
print(df[["price", "interval_band"]])Exercise
Which function should you use for three fixed price ranges, and which should you use for the bottom 50% and top 50% of values?
Show answer
Use pd.cut for the fixed price ranges and pd.qcut with q=[0, 0.5, 1] for the two distribution-based groups.