pandas · difficulty ◆◆
pandas cut() — turn continuous numbers into labelled bins
cut() writes the 'Low / Medium / High' column — you pick the edges, pandas sorts everyone into them.
The Low / Medium / High column on every dashboard you have ever read comes from one line of pandas and one flag that nobody reads.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ pd.cut()- 0.8.0
- added in pandas
- 9
- parameters
- min/max ± 0.1%
- int bins edge rule
- since 0.20.0
- IntervalIndex categories
29 June 2012 — same release as qcut
x, bins, right, labels, retbins, precision, include_lowest, duplicates, ordered — pandas 3.0.3 signature
docstring: 'the range of x is extended by .1% on each side to include the minimum and maximum values'
May 2017 — before that the categories were labels without comparable edges
What it does
cut() takes a continuous column and a set of edges, and returns the same length of data as an ordered categorical: one band per value. You give it bins as an explicit list of edges ([0, 100, 500, 1000]), or as an integer and it derives equal-width edges from the min and max. labels= replaces the interval objects with words your reader understands. retbins=True hands the computed edges back to you, so a later batch can be cut into exactly the same bands.
Why it matters
You cannot group a float. Grouping by amount_eur gives you one group per cent; grouping by region gives you five rows. cut() is the collapse in between — it is how a numeric column becomes reportable. It is also the cheapest feature engineering in the library: three lines and a raw transaction log turns into a band-by-week revenue table that a sales director can read. Every threshold you have ever put in a CASE WHEN has a cut() equivalent.
Example
$ import pandas as pd, numpy as np
orders = pd.DataFrame({
"order_id": [1001, 1002, 1003, 1004, 1005, 1006],
"city": ["Yanbu", "Jubail", "Riyadh", "Yanbu", "Jubail", "Dammam"],
"amount_eur": [42.50, 187.00, 1290.00, 999.99, 75.25, 310.00],
})
orders["band"] = pd.cut(
orders["amount_eur"],
bins=[0, 100, 500, 1000, np.inf],
labels=["small", "mid", "large", "enterprise"],
)
print(orders.to_string())
print()
print(orders.groupby("band", observed=True)["amount_eur"].agg(["count", "sum"])) order_id city amount_eur band
0 1001 Yanbu 42.50 small
1 1002 Jubail 187.00 mid
2 1003 Riyadh 1290.00 enterprise
3 1004 Yanbu 999.99 large
4 1005 Jubail 75.25 small
5 1006 Dammam 310.00 mid
count sum
band
small 2 117.75
mid 2 497.00
large 1 999.99
enterprise 1 1290.00Explicit edges plus labels: order amounts become small / mid / large / enterprise, and the categorical keeps label order, so groupby and sort follow the business ladder rather than the alphabet. Pass observed=True or you will also get a row for every band that happens to be empty.
$ import pandas as pd
temps = pd.Series([18.0, 22.1, 26.8, 31.5, 35.2, 29.9, 24.0], name="temp_c")
print(pd.cut(temps, bins=[18, 25, 32, 40]).value_counts(dropna=False))
print()
print(pd.cut(temps, bins=[18, 25, 32, 40], include_lowest=True).value_counts())temp_c
(25.0, 32.0] 3
(18.0, 25.0] 2
(32.0, 40.0] 1
NaN 1
Name: count, dtype: int64
temp_c
(17.999, 25.0] 3
(25.0, 32.0] 3
(32.0, 40.0] 1
Name: count, dtype: int6418.0 disappears because cut() is right-closed by default — (18, 25] excludes 18 itself, so the minimum value becomes NaN without an error. Anything below the lowest edge or above the highest does the same. include_lowest=True widens only the first interval's left edge.
$ import pandas as pd, numpy as np
rng = np.random.default_rng(7)
monday = pd.Series(rng.uniform(0.5, 9.5, 2000), name="vibration_mm_s")
labels = ["ok", "watch", "alert", "shutdown"]
buckets, edges = pd.cut(monday, bins=[0, 2.75, 5.0, 7.25, 10],
labels=labels, retbins=True)
print("edges:", edges)
print(monday.groupby(buckets, observed=True).size().to_string())
print()
tuesday = pd.Series([1.2, 4.9, 7.8, 9.1], name="vibration_mm_s")
print(pd.cut(tuesday, bins=edges, labels=labels).to_string())edges: [ 0. 2.75 5. 7.25 10. ]
vibration_mm_s
ok 486
watch 527
alert 478
shutdown 509
0 ok
1 watch
2 shutdown
3 shutdown
Categories (4, str): ['ok' < 'watch' < 'alert' < 'shutdown']retbins=True returns the edges the first call computed. Feed them into Tuesday's readings and the alarm bands stay identical. If you instead call pd.cut(batch, bins=4) on each new batch, pandas derives fresh edges from that batch's min and max — the labels survive, the thresholds silently move.
$ import pandas as pd, numpy as np
spend = pd.Series(np.random.default_rng(7).lognormal(4, 1, 1000), name="spend_eur")
print(pd.cut(spend, bins=4).value_counts().sort_index().to_string())
print()
print(pd.qcut(spend, 4).value_counts().sort_index().to_string())spend_eur
(1.402, 180.226] 912
(180.226, 358.338] 65
(358.338, 536.45] 18
(536.45, 714.561] 5
spend_eur
(2.113, 27.657] 250
(27.657, 51.016] 250
(51.016, 96.337] 250
(96.337, 714.561] 250Same column, two philosophies. cut(bins=4) splits the width evenly, so a lognormal spend column dumps 912 of 1000 rows into the first band. qcut(4) splits the count evenly: 250 each. Business thresholds → cut. Percentile cohorts → qcut.
Common flags
- bins
- int → equal-width edges derived from min/max (extended 0.1% each side); sequence → your explicit edges; IntervalIndex → re-use the categories of an earlier cut without rebuilding them
- labels
- List of names, one per interval — or False to get integer codes 0..n-1 instead of Interval objects
- right
- Default True, i.e. edges are (a, b]; right=False flips to [a, b). Decide once per project and stop mixing them
- include_lowest
- Extends the first interval's left edge so the minimum value is not dropped into NaN by right=True
- retbins
- Return (result, edges) — the edge array is what makes the same bands replayable on next month's data
- precision
- Digits used when formatting interval labels; display only, the stored edges keep full float precision
- duplicates
- 'raise' by default; 'drop' discards non-unique edges (the flag qcut needs on lumpy data, accepted by cut too)
History
Added in pandas 0.8.0 — 29 June 2012
cut() and qcut() shipped together in pandas 0.8.0, and the release notes are disarmingly direct about where they came from: 'New cut and qcut functions (like R's cut function) for computing a categorical variable from a continuous variable by binning values either into value-based (cut) or quantile-based (qcut) bins.' R's base::cut had been doing this since the 1990s. pandas in mid-2012 was still pre-1.0 and pre-Categorical: the same release renamed Factor to Categorical, which is why the early cut() returned something that felt like a labelled Factor.
0.20.0, 5 May 2017: the intervals became real objects
For five years the bins existed mostly as labels. pandas 0.20.0 gave cut() and qcut() a real IntervalIndex as their categories, so the edges themselves became queryable: you can compare them, join on them, and pass c.cat.categories straight back in as bins. The same release added datetime64 and timedelta64 support (GH 14714), which is what made cutting by time window with Timestamp edges natural. In 1.1.0 (July 2020) the ordered parameter arrived, letting you cut with duplicate labels instead of raising.
Under the hood
Under the hood: codes, intervals, and a binary search
A cut() result is a pandas Categorical — per row an integer code (int8 up to int32 depending on the number of bins) pointing into a list of Interval objects. The band column therefore costs a handful of bytes per row no matter how long the label is; you are storing codes, not strings. The edges themselves live in an IntervalIndex whose get_indexer() binary-searches the sorted edges (O(log n) per value) instead of comparing each value against every edge. Pass bins as an IntervalIndex — the c.cat.categories trick — and pandas skips edge construction entirely and goes straight to the lookup; pandas 1.0.0 lists a performance improvement for exactly that path (GH 27668). Missing values never get a code, which is precisely why out-of-range rows vanish quietly rather than raising.
Fun facts
Pros & cons
pros
- + One line turns a float column into an ordered categorical you can group, sort and plot
- + labels decouple the arithmetic from the wording — rename 'small/mid/large' without touching a single edge
- + retbins makes bands reproducible across batches, which is the whole game in reporting
cons
- − Right-closed by default: the minimum value, and anything outside your edges, silently becomes NaN
- − int bins derives ugly edges from min and max — never the round thresholds you would have picked
- − The result is a categorical, so code expecting strings needs astype(str) and code expecting numeric needs codes
Takeaways
- 1Pass explicit edges for business bands; pass an integer only when you truly want equal width.
- 2After every cut, check result.isna().sum() — out-of-range values fail without a warning.
- 3Set include_lowest=True whenever your lowest edge equals the smallest real value in the column.
- 4Use retbins=True once and reuse the edges: bins recomputed per batch drift and break comparisons.
- 5Percentile cohorts are qcut's job — equal width and equal count answer different questions.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
