In pandas, when do you bin a credit-score column with `pd.cut` and when with `pd.qcut`, and what do their defaults do to edge values?
answer
- fixed edges versus equal counts
- intervals closed on the right
- lowest edge left out
- labels one fewer than edges
- duplicate quantile edges raise
basics
~20 spd.cut uses edges you choose, such as policy thresholds; pd.qcut picks edges at quantiles so bins hold about equal counts. cut's intervals are right-closed, so the lowest edge is excluded unless include_lowest=True, and values outside the edges become NaN.
solid answer
~40 sI use `pd.cut` when the thresholds mean something, such as risk tiers at fixed credit scores: `pd.cut(df["score"], bins=[300, 580, 670, 740, 850], labels=[...])`. I use `pd.qcut` when I want equal-sized groups, such as quartiles of income, and accept that the edges move with the data. Both return an ordered categorical. The defaults bite at the edges: `right=True` makes intervals like `(300, 580]`, so a score of exactly 300 becomes NaN unless I pass `include_lowest=True`, and anything outside the edges is NaN too. `labels` needs one fewer entry than the edges. On skewed data `qcut` can produce repeated edges and raises a ValueError unless `duplicates="drop"`.
code
python · 17 linesimport pandas as pd
scores = pd.Series([300, 580, 581, 700, 900])
edges = [300, 580, 670, 740, 850]
names = ["high", "elevated", "moderate", "low"]
print(pd.cut(scores, bins=edges, labels=names).tolist())
# [nan, 'high', 'elevated', 'moderate', nan]
print(pd.cut(scores, bins=edges, labels=names, include_lowest=True).tolist())
# ['high', 'high', 'elevated', 'moderate', nan]
income = pd.Series([0, 0, 0, 0, 0, 0, 41000, 87000])
try:
pd.qcut(income, q=4)
except ValueError as err:
print(err) # Bin edges must be unique ...
print(pd.qcut(income, q=4, duplicates="drop").cat.categories)go deeper
Recall that cut uses edges you give and qcut uses quantiles, and that both return a categorical of intervals or labels.
Explain right-closed intervals, include_lowest, NaN for out-of-range values, the labels count and qcut's duplicate-edge error.
Reuse saved edges through retbins so bins stay stable across data loads, and check value_counts(dropna=False) for rows that fell outside.
Decide whether tiers are policy or distribution: fixed thresholds belong in reviewed configuration, quantile tiers need their edges recorded with each run.
## Two ways to turn a number into a bucket Binning, also called discretization, replaces a continuous value with the interval it falls into. pandas has two functions for it, and the choice between them is a choice about **where the edges come from**. | | `pd.cut(x, bins, ...)` | `pd.qcut(x, q, ...)` | |---|---|---| | Edges come from | you, or equal-width splits of the range | the data's quantiles | | Bin sizes | can be very uneven | about equal counts | | Typical use | policy thresholds, age bands, score tiers | quartiles, deciles, top-10% flags | | Edges on new data | stay fixed | move with the data | | Signature defaults | `right=True`, `include_lowest=False`, `duplicates="raise"`, `ordered=True` | `duplicates="raise"` | Both return a **categorical** whose categories are ordered intervals, or your `labels` if you pass them. Because the categories are ordered, comparisons such as `tier < "moderate"` and sorting follow the bin order rather than alphabetical order. ## `pd.cut` with explicit edges For a loan table scored into risk tiers, the thresholds are business rules, so `cut` is the right tool: ```python pd.cut(loans["score"], bins=[300, 580, 670, 740, 850], labels=["high", "elevated", "moderate", "low"]) ``` The defaults decide what happens at the edges: - **`right=True`** makes every interval closed on the right: `(300, 580]`, `(580, 670]` and so on. A score of exactly 580 is high risk, and 581 is elevated. - Because the first interval is open on the left, a value equal to the **lowest edge** (300) falls in no bin and becomes **NaN**. `include_lowest=True` widens the first interval to take it in. - `right=False` flips the convention to `[300, 580)`, which is what you want when a threshold reads "580 and above". - A value **outside** all edges, such as a data-entry 900 against a top edge of 850, also becomes **NaN**, with no warning. - **`labels`** must have exactly one fewer entry than `bins`; otherwise `cut` raises a ValueError. Passing an integer, such as `bins=4`, asks for four **equal-width** bins over the observed range, which pandas widens slightly so the minimum and maximum are included. That is rarely what a business rule means. ## `pd.qcut` on quantiles `pd.qcut(x, q=4)` computes the quartile edges of the data and bins on them, so each bin holds roughly a quarter of the rows. `q` can also be a list of quantiles, such as `[0, 0.5, 0.9, 1.0]`. The trade-offs: 1. The **edges change** when the data changes, so a "top quartile" label means something different next month. 2. On **skewed or heavily tied data**, several quantiles can land on the same value. `qcut` then raises `ValueError: Bin edges must be unique`, and suggests `duplicates="drop"`. 3. With `duplicates="drop"` you get **fewer bins than asked for**, so a fixed list of four `labels` no longer fits and raises its own ValueError. ## Shaping the output A few more arguments change what comes back rather than where rows go: - `labels=False` returns only the **integer bin number** of each row, which is handy as a model feature or a sort key. - `ordered=False` (on `cut`, with labels) gives an unordered categorical, so labels may repeat, for example two edges both named `"standard"`. - Without `labels`, the categories are `Interval` objects, which print as `(580.0, 670.0]` and can be inspected with `.cat.categories`. ## Edge cases worth checking after binning - Missing input stays **NaN** in the output; neither function assigns it a bin. - Count the result with `value_counts(dropna=False)` to see rows that fell outside the edges. - `retbins=True` returns the edges as well, so you can save qcut's edges and reuse them with `cut` on new data, which keeps the buckets stable. - `precision` (default 3) sets the precision at which the interval labels are stored and displayed; it does not move the edges a row is tested against. ## Compared with `np.select` `np.select` handles arbitrary conditions over several columns. `cut` is narrower but clearer when the rule is just "which range of one numeric column", and it hands back an ordered categorical for free. A rule that mixes a score range with a debt-to-income test belongs in `np.select` or `Series.case_when`. ## Summary - Fixed, meaningful thresholds: **`cut`** with explicit `bins` and `labels`. - Equal-sized groups: **`qcut`**, knowing its edges move. - Watch the **right-closed** default, the **lowest edge**, out-of-range values and **duplicate quantile edges**.
- How do you apply last quarter's quartile edges to this quarter's loans?Call `pd.qcut(old, q=4, retbins=True)` to get the edges back, store them, and bin the new data with `pd.cut(new, bins=edges, include_lowest=True)`. Calling `qcut` on the new data would recompute the edges, so the same label would mean a different range.
- Why does `qcut(..., duplicates="drop", labels=["q1", "q2", "q3", "q4"])` still fail on tied data?Dropping duplicate edges leaves fewer intervals than four, and `labels` must have exactly one entry per interval. pandas raises a ValueError about the label count. Either let pandas name the intervals, or compute the edges first and build labels to match.
- Believes pd.cut includes the lowest edge by default
- Uses qcut for fixed business thresholds and expects stable edges
- Passes as many labels as there are bin edges
- Assumes out-of-range values go into the nearest bin
- Thinks qcut always returns exactly q bins