Sub topic 4
Which side is closed: right and include_lowest
This chapter assumes you can call pd.cut with a list of bin edges and read a pandas Series. It covers one question: when a value sits exactly on a bin edge, which bin does it go to, and what happens if no bin claims it?
Why edge values need a rule
Bin edges are shared. With edges [0, 18, 65, 120], the number 18 is the upper boundary of the first range and the lower boundary of the second. Bins cannot overlap, so pd.cut needs a fixed rule to decide where 18 goes.
In mathematical notation, (a, b] means "greater than a, up to and including b". Round brackets exclude the edge and square brackets include it. Two parameters control this:
right(defaultTrue) decides which end of each interval is closed.include_lowest(defaultFalse) decides whether the very first edge is included when intervals are closed on the right.
Ages, prices, and test scores often land exactly on round edges like 18, 100, or 60. The default rule can silently turn those values into NaN.
The default: closed on the right
With right=True, every interval is (left, right]. A value equal to an edge goes to the interval that ends at that edge. The first edge, however, is only ever a left boundary, and left boundaries are open, so it belongs to no interval.
import pandas as pd
values = pd.Series([0, 10, 15, 20])
edges = [0, 10, 20]
default = pd.cut(values, bins=edges)
print(default.isna().tolist())
print(default.cat.categories.closed)The bins are (0, 10] and (10, 20]. The results are:
| value | bin |
|---|---|
| 0 | NaN (not in `(0, 10]`) |
| 10 | `(0, 10]` |
| 15 | `(10, 20]` |
| 20 | `(10, 20]` |
The script prints [True, False, False, False] and then right. The last edge, 20, is included, but the first edge, 0, is lost.
Keeping the lowest edge with include_lowest
Set include_lowest=True to make the first interval closed on both ends. The first interval becomes [0, 10] and the other intervals stay as they were.
import pandas as pd
values = pd.Series([0, 10, 15, 20])
edges = [0, 10, 20]
lowest = pd.cut(values, bins=edges, include_lowest=True)
print(lowest.isna().sum())
print(lowest.cat.categories[0])The first line prints 0, because no value is missing any more. The second line shows the first interval, which pandas displays as (-0.001, 10.0]. The left end is shifted down by 0.001 only so the printed label shows that the interval reaches below 0. The real membership test is still "from 0 inclusive". The shift follows the precision parameter, which controls how many decimal places appear in labels. It does not change which values are assigned.
A common mistake is building edges from the data itself:
import pandas as pd
scores = pd.Series([50, 60, 70, 80, 90])
edges = [scores.min(), 70, scores.max()]
without = pd.cut(scores, bins=edges)
with_lowest = pd.cut(scores, bins=edges, include_lowest=True)
print(without.isna().sum())
print(with_lowest.isna().sum())This prints 1 and then 0. Without include_lowest, the minimum score of 50 falls on the open left edge and becomes NaN. The maximum is safe because the last edge is closed on the right.
Flipping the sides with right=False
Setting right=False makes every interval [left, right). A value equal to an edge now goes to the interval that starts at that edge. The first edge is included, and the last edge is excluded.
import pandas as pd
values = pd.Series([0, 10, 15, 20])
edges = [0, 10, 20]
left_closed = pd.cut(values, bins=edges, right=False)
print(left_closed.isna().tolist())
print(left_closed.cat.categories.closed)The bins are [0, 10) and [10, 20):
| value | bin |
|---|---|
| 0 | `[0, 10)` |
| 10 | `[10, 20)` |
| 15 | `[10, 20)` |
| 20 | NaN (not in `[10, 20)`) |
The script prints [False, False, False, True] and then left. The loss has moved from the bottom edge to the top edge.
How the two parameters combine
| `right` | `include_lowest` | Intervals | First edge included | Last edge included |
|---|---|---|---|---|
| `True` | `False` | `(a, b]`, `(b, c]` | No | Yes |
| `True` | `True` | `[a, b]`, `(b, c]` | Yes | Yes |
| `False` | `False` | `[a, b)`, `[b, c)` | Yes | No |
| `False` | `True` | `[a, b)`, `[b, c)` | Yes | No |
The last row is a trap. include_lowest only acts on the first edge, and with right=False that edge is already included. It does not make the last interval closed at the top. To keep the maximum value when right=False, put a higher edge at the end, such as np.inf or a number above the largest value.
The flowchart traces a value that equals an edge.
Choosing a convention that matches the rule you are encoding
The right setting is the one that matches how the category is defined in the real world. Write the rule in words first, then pick the parameters.
- "18 and under is a child": 18 belongs with the lower group, so use the default
right=True. - "Adults start at 18": 18 belongs with the upper group, so use
right=False.
Here is the second rule applied with an open-ended top bin:
import numpy as np
import pandas as pd
ages = pd.Series([0, 17, 18, 64, 65, 90])
bins = [0, 18, 65, np.inf]
labels = ["child", "adult", "senior"]
groups = pd.cut(ages, bins=bins, labels=labels, right=False)
print(pd.DataFrame({"age": ages, "group": groups}))Ages 0 and 17 are children, 18 and 64 are adults, and 65 and 90 are seniors. Using np.inf as the last edge keeps the maximum age inside a bin, and right=False puts 18 and 65 in the group that starts there. No value is NaN, because 0 sits on the closed left edge and nothing reaches the infinite upper edge.
Keep the convention uniform across a project. If one report counts 65 as a senior and another counts it as an adult, their totals will not match, and the cause is hard to find later.
Checking what you built
Do not rely on remembering the defaults. Inspect the result:
result.cat.categoriesshows the intervals, and its.closedattribute returns"right"or"left".result.isna().sum()counts values that no bin accepted.values[result.isna()]lists the unassigned values, which are often edge values.
import pandas as pd
values = pd.Series([5, 10, 15])
result = pd.cut(values, bins=[5, 10, 15])
print(values[result.isna()])This prints the row with value 5. Seeing the offending values usually makes the fix clear.
Edge cases to watch
- Edges must increase. A list such as
[0, 20, 10]raises aValueErrorsaying the bins must increase monotonically. - Floating-point edges can surprise you. A value computed as
0.1 + 0.2is slightly above0.3, so it lands above an edge written as0.3. For exact thresholds, work in integers (for example cents) or round the data first. include_lowestchanges nothing for a value that is not equal to the first edge. It is safe to leave on when you build edges fromvalues.min().- Missing input is a separate cause of
NaN. ANaNin the data staysNaNin the output regardless ofrightandinclude_lowest, so checkvalues.isna().sum()before blaming the edges.
Exercise
Given values = pd.Series([5, 10, 15]) and bins = [5, 10, 15], which values become NaN for each of these calls? (a) pd.cut(values, bins) (b) pd.cut(values, bins, include_lowest=True) (c) pd.cut(values, bins, right=False) (d) pd.cut(values, bins, right=False, include_lowest=True)
Show answer
(a) 5 is NaN, because the default intervals (5, 10] and (10, 15] leave out the first edge. (b) No value is NaN, because the first interval becomes [5, 10]. (c) 15 is NaN, because the intervals [5, 10) and [10, 15) leave out the last edge. (d) 15 is still NaN, because include_lowest has no effect when right=False. To keep 15, add a higher final edge such as np.inf.
Exercise
A shop gives free shipping to orders of 50 or more and charges shipping below 50. Which right setting should you use with bins=[0, 50, np.inf] and labels=["pay", "free"], and why?
Show answer
Use right=False. The intervals are [0, 50) and [50, inf), so an order of exactly 50 lands in "free", which matches the rule. With the default right=True, a 50 order would fall in (0, 50] and be charged. An order of 0 is also included in the first bin with right=False, whereas the default would turn it into NaN.