quantile-edges
Data-driven bin edges that keep every bin statistically reliable.
quantile-edges builds bins from the data itself, not from ranges you decide in advance. It guarantees that each bin carries a minimum number of observations, so any statistic you compute per bin (an average, a rate, a share) rests on enough data to mean something.
It has two entry points:
bin_edgesworks on one array of values and returns bin edges.bin_rulesworks on a whole DataFrame and returns rule strings (">= 21","1 to 20") for every numeric column.
from quantile_edges import bin_edges
values = list(range(1, 101))
# 1. Bins of 25% each -> 4 bins, 10 ranges in total
bin_edges(values, ranges=True, bin_pct=25)
# [(1, 25), (26, 50), (51, 75), (76, 100),
# (1, 50), (1, 75), (1, 100),
# (26, 75), (26, 100),
# (51, 100)]
# 2. The same bins, returned as boundaries
bin_edges(values, ranges=False, bin_pct=25)
# [1, 26, 51, 76, 100]
ranges is required, and every option after values is keyword-only. By default each call also prints a small summary table of the bins; pass display=False to turn it off. The examples here show return values only.
Purpose
A statistic is only as trustworthy as the number of observations behind it. A bin holding 4 rows gives a wild average, while a bin holding 4,000 gives a stable one, and comparing the two is misleading.
quantile-edges solves this at the source:
- Bins come from the data. Edges are calculated from what is in your data, so they adapt when the data changes and need no hand-picked ranges.
- Every bin carries enough data. A minimum bin size (
min_bin_n) is always enforced, so averages, rates and shares computed per bin rest on a sample that means something. - Identical values stay together. Ties are never split across bins, so a value always belongs to exactly one bin.
This is useful for charts, scorecards, risk bands, cohort analysis and anywhere you group a numeric column before aggregating.
Bins do not have to be equal. They are as even as the rules allow, and uneven only where ties or the minimum size require it.
Three terms are used throughout: a bin is a base slice of the population, a range is a (lower, upper) pair that can span one bin or several neighbouring bins, and a rule is a condition string built from the edges (such as ">= 21" or "1 to 20") that you can apply to a column to select rows.
Parameters
bin_edges(
values,
*,
ranges,
bin_pct=20,
min_bin_n=10,
display=True,
)
| Parameter | Type | Default | Meaning |
|---|---|---|---|
values |
array-like | required | Numeric observations (list, tuple, numpy array, pandas Series). Must be finite numbers; empty input raises. |
ranges |
bool | required | True returns every range that can be built from the bins (the bins themselves first, then wider ranges). False returns the bin boundaries as one sorted list: the lower edge of every bin, then the upper edge of the last bin. |
bin_pct |
number, 0 < x <= 100 |
20 |
Share of the data each bin should carry. |
min_bin_n |
int, >= 1 |
10 |
Minimum observations in any bin. Always enforced: the larger of this and what bin_pct asks for wins. |
display |
bool | True |
Prints a small table with one row per bin (its range, count and share); the combined ranges are not listed. The return value is the same either way. Pass False to print nothing. |
What you get back
ranges=True: every range the bins can form
A range starts at the lower edge of one bin and ends at the upper edge of the same or a later bin, so the bins act as the guide for where every range starts and ends. The base bins come first, then the wider ranges grouped by start bin.
bin_edges(range(1, 101), ranges=True) # default bin_pct=20 -> 5 bins
# [(1, 20), (21, 40), (41, 60), (61, 80), (81, 100),
# (1, 40), (1, 60), (1, 80), (1, 100),
# (21, 60), (21, 80), (21, 100),
# (41, 80), (41, 100),
# (61, 100)]
All 15 possible ranges: the 5 base bins, then the 4 ranges starting at 1, the 3 starting at 21, the 2 starting at 41 and the 1 starting at 61.
Every returned range contains at least min_bin_n observations, because each one includes at least one full bin.
The output grows quickly with the number of bins. k bins give k * (k + 1) / 2 ranges:
| Bins | Ranges returned |
|---|---|
| 5 | 15 |
| 10 | 55 |
| 20 | 210 |
| 50 | 1,275 |
| 100 | 5,050 |
| 1,000 | 500,500 |
The number of bins comes from bin_pct (100 / bin_pct, roughly) and is limited by min_bin_n. A very small bin_pct on a large dataset can therefore produce a very large list, so keep bin_pct in a sensible range for the size of your data.
ranges=False: the bin boundaries
One sorted list: the lower edge of every bin, followed by the upper edge of the last bin. Each bin runs from its own value up to, but not including, the next value in the list, and the last bin also includes its final value.
bin_edges(range(1, 1000), ranges=False, bin_pct=20, display=False)
# [1, 201, 401, 601, 999]
These boundaries describe the bins 1 to 200, 201 to 400, 401 to 600 and 601 to 999. The last bin is larger because a small leftover was merged into it (see How it works).
If the last bin holds a single repeated value, that value appears twice at the end, so that bin keeps its own interval:
bin_edges([1]*10 + [2]*10, ranges=False, bin_pct=50, min_bin_n=5, display=False)
# [1, 2, 2]
A single bin is allowed. If bin_pct and min_bin_n ask for as much as the data holds, one bin carries all of it (see the example below).
How it works
- The values are sorted and grouped by distinct value.
- Each bin's target size is set:
max(share, min_bin_n), where the share isbin_pctpercent of all the data. - Distinct values are added to the current bin until it reaches its target, then it closes. A group of identical values is never split, so a bin can end up slightly larger than its target.
- If the last bin is left below target, it is merged into the previous one.
- The lowest and highest value actually found in each bin become its edges.
- With
ranges=True, every continuous range is then built from the bins: start at the lower edge of one bin and end at the upper edge of the same or a later bin. - With
ranges=False, the lower edge of every bin is returned, followed by the upper edge of the last bin.
Bin rules for a DataFrame
bin_rules runs bin_edges on every numeric column of a DataFrame and turns the edges into rule strings. Non-numeric columns and the hit column are skipped.
bin_rules(
df,
bin_pct=20,
min_bin_n=10,
directions="all",
display=True,
)
| Parameter | Type | Default | Meaning |
|---|---|---|---|
df |
pandas DataFrame | required | Must have at least one numeric column besides hit. The hit column is always skipped. |
bin_pct |
number, 0 < x <= 100 |
20 |
Share of the data each bin should carry. Same as in bin_edges. |
min_bin_n |
int, >= 1 |
10 |
Minimum observations in any bin. Same as in bin_edges. |
directions |
str or dict | "all" |
Which rules to build (see below). A dict maps column name to a direction; columns not in the dict use "all". |
display |
bool | True |
Prints the rules per column. The return value is the same either way. |
Directions
| Direction | Rules produced | Built from |
|---|---|---|
"all" |
">= e", "<= e" and "lo to hi" |
both edge types |
"right" |
">= e" only |
cut edges (ranges=False) |
"left" |
"<= e" only |
cut edges (ranges=False) |
"range" |
"lo to hi" only |
range edges (ranges=True) |
A range whose two ends are equal is written as "= x" instead of "x to x".
Example: several columns
import pandas as pd
from quantile_edges import bin_rules
n = 100
df = pd.DataFrame({
"age": range(1, n + 1), # 1, 2, ..., 100 (all distinct)
"income": range(10, 10 * n + 1, 10), # 10, 20, ..., 1000 (all distinct)
"score": [i % 10 for i in range(n)], # 0-9, each value 10 times (ties)
"city": ["Lagos", "Abuja"] * (n // 2), # text column, skipped
"hit": [0, 1] * (n // 2), # skipped
})
# Per-column directions. Any numeric column left out of the dict uses "all".
directions = {
"age": "range", # ranges only
"income": "right", # ">=" rules only
"score": "left", # "<=" rules only
}
rules = bin_rules(
df,
bin_pct=25,
min_bin_n=10,
directions=directions,
display=True,
)
print(list(rules)) # ['age', 'income', 'score']
With bin_pct=25 on 100 rows, each bin targets 25 rows:
age: 4 bins (1 to 25, 26 to 50, 51 to 75, 76 to 100).income: 4 bins (10 to 250, 260 to 500, 510 to 750, 760 to 1000).score: each value appears 10 times and ties are never split, so bins close at 30 rows (0 to 2, then 3 to 5, then 6 to 8). The leftover value 9 has only 10 rows, below the 25 target, so it merges into the last bin. That leaves 3 bins: 0 to 2, 3 to 5 and 6 to 9.
Printed output (wrapped here; the real print puts each list on one line):
BIN RULES.
age : ['1 to 25', '26 to 50', '51 to 75', '76 to 100',
'1 to 50', '1 to 75', '1 to 100',
'26 to 75', '26 to 100',
'51 to 100']
income : ['>= 10', '>= 260', '>= 510', '>= 760', '>= 1000']
score : ['<= 0', '<= 3', '<= 6', '<= 9']
The same df with one direction for every column:
bin_rules(df, bin_pct=25, directions="right", display=False)
# {"age": [">= 1", ">= 26", ">= 51", ">= 76", ">= 100"],
# "income": [">= 10", ">= 260", ">= 510", ">= 760", ">= 1000"],
# "score": [">= 0", ">= 3", ">= 6", ">= 9"]}
With "all", age and income get 5 + 5 + 10 = 20 rules each, and score gets 4 + 4 + 6 = 14.
Building blocks
bin_rules is two steps run together. Both are also available from quantile_edges.rules:
| Function | What it does |
|---|---|
get_bin_edges(df, ...) |
Returns (range_edges, cut_edges), each a dict of column to edges. |
edges_to_rules(range_edges, cut_edges, ...) |
Turns those two dicts into a dict of column to rule strings. |
get_bin_edges takes the same bin_pct, min_bin_n and directions as bin_rules.
Things to know
- Some rules match everything.
">= first edge","<= last edge"and the full-span range ("1 to 100"above) match every row, so they carry no information for scoring. - The
<=rules use bin boundaries. The cut edges are lower edges, so"<= 26"includes the first value of the second bin, not only the first bin. - NaNs raise. Missing values in a numeric column raise an error from
bin_edges, so drop or fill them first. - Large frames can produce long lists. Rules include every range, so the output grows with the number of bins (see the table above).
Examples
Ties are never split
ties = [1]*30 + [2]*5 + [3]*25 + [4]*20 + [5]*20
bin_edges(ties, ranges=True, bin_pct=25, min_bin_n=10)
Quantile_edges
bin_pct = 25%
min_bin_n = 10 | 100 observations
-----------------------------------
# Range Count %
-----------------------------------
1 1 to 1 30 30.0%
2 2 to 3 30 30.0%
3 4 to 5 40 40.0%
-----------------------------------
Total 100 100.0%
Every value 1 stays together even though that bin (30) is bigger than the 25% target. The table lists the 3 bins; the function itself returns all 6 ranges built from them.
One bin carries everything
bin_edges(range(1, 21), ranges=True, min_bin_n=50, display=False)
# [(1, 20)]
bin_edges(range(1, 21), ranges=False, min_bin_n=50, display=False)
# [1, 20]
min_bin_n=50 asks for more observations than the 20 available, so a single bin holds them all.
A minimum bin size you can rely on
bin_edges(range(1, 101), ranges=True, bin_pct=5, min_bin_n=30, display=False)
# [(1, 30), (31, 60), (61, 100), (1, 60), (1, 100), (31, 100)]
# 5% bins were asked for, but no bin holds fewer than 30 rows
Errors
bin_edges raises ValueError with a message that says how to fix it. bin_rules also raises TypeError for wrong types. Common ones:
| Situation | Error | Message (shortened) |
|---|---|---|
| Empty input | ValueError |
values is empty. |
NaN, infinity, text or booleans in values |
ValueError |
values must contain finite numeric values. |
bin_pct outside 0 to 100 |
ValueError |
bin_pct must be a number between 0 and 100. |
df is not a DataFrame |
TypeError |
df must be a pandas DataFrame, got ... |
df has no columns |
ValueError |
df has no columns. |
No numeric columns besides hit |
ValueError |
df has no numeric feature columns ... |
directions value is not a string |
TypeError |
direction for ... must be a string, got ... |
directions value is not all, left, right or range |
ValueError |
direction for ... must be one of ... |
directions dict has a column not in df |
ValueError |
direction columns not in df: [...] |
bin_rules needs pandas. bin_edges works without it.
Metadata
Release files for quantile-edges 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| quantile_edges-1.0.0.tar.gz | 16.5 kB | Without provenance | Details for quantile_edges-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| quantile_edges-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for quantile_edges-1.0.0-py3-none-any.whl |
Total release size: 29.4 kB
Release files / quantile_edges-1.0.0.tar.gz
| Download URL | quantile_edges-1.0.0.tar.gz |
|---|---|
| Size | 16.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bd510a09c87dbe34063c70ba53ba50ff3c96a3cbf5f2906c221e02b9fa6d6bcc
|
|
BLAKE2b-256 checksum How to use checksums |
2d0f3dc3c8595a5a111b2f65c9ffd0cdb7f244da1a91e56e2c7e1b62c2da5f1c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.9
|
Release files / quantile_edges-1.0.0-py3-none-any.whl
| Download URL | quantile_edges-1.0.0-py3-none-any.whl |
|---|---|
| Size | 12.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f05a7599e7785e8c3626308376db3c9a4e880c07432d2068ec9c195a8ad8bc6c
|
|
BLAKE2b-256 checksum How to use checksums |
4b1574acca492aced4104339f691e9fd473aca1a390c5c7406c9683c1519decb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.9
|
Security for quantile-edges 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.