bin_numeric
bin_numeric(x, breaks, labels, right=False, quiet=False)Bin a numeric vector into labelled groups.
A survey-friendly binning helper that returns a categorical in band order and uses left-closed, right-open intervals by default so that age bands like 18-21 behave intuitively.
Bands are built as R’s cut() builds them with include.lowest = TRUE, so the very lowest break is included. With right=False (the default) a band runs from its lower break up to but not including the next, i.e. [18, 25). Text input is salvaged with ensure_numeric(), so “27 years” bins correctly. The result is a categorical whose categories follow labels, so tables and charts built from it list the bands low to high (“40-70k” before “100-150k”) rather than alphabetically. Call .astype(object) on it if you need plain text.
A value below the first break or above the last becomes missing and drops out of every chart built from the result, so the function says how many did and what their range was. A closed top band such as 35 to 40.5 under a label of “35 to 40+” is the usual cause; math.inf is what that label means.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | list or Series | Numbers. | required |
| breaks | list of float | Cut points. With n labels you need n + 1 breaks. Use math.inf for an open-ended top band. |
required |
| labels | list of str | Group labels, one fewer than breaks. |
required |
| right | bool | If True, intervals are closed on the right; if False (default) closed on the left. | False |
| quiet | bool | If True, do not report values that fell outside breaks. |
False |
Returns
| Name | Type | Description |
|---|---|---|
| pandas.Series | A categorical whose categories are labels in the order given (values outside the range or missing become missing). |
See Also
recode_age, ensure_numeric
Examples
>>> import math
>>> bin_numeric([15, 19, 27, 41], breaks=[0, 18, 25, 35, math.inf],
... labels=["<18", "18-24", "25-34", "35+"])