quantile-edges 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from bisect import bisect_left
|
|
3
|
+
from itertools import accumulate, groupby
|
|
4
|
+
from math import ceil, isfinite
|
|
5
|
+
from numbers import Integral, Real
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import numpy as _np
|
|
9
|
+
|
|
10
|
+
_BOOL_TYPES = (bool, _np.bool_)
|
|
11
|
+
except ImportError:
|
|
12
|
+
_np = None
|
|
13
|
+
_BOOL_TYPES = (bool,)
|
|
14
|
+
|
|
15
|
+
# Name shown at the top left of the display table.
|
|
16
|
+
PY_NAME = "Quantile_edges"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _fmt(value):
|
|
20
|
+
"""Readable number: thousands separators, no stray decimals."""
|
|
21
|
+
if isinstance(value, Integral):
|
|
22
|
+
return f"{int(value):,}"
|
|
23
|
+
|
|
24
|
+
value = float(value)
|
|
25
|
+
|
|
26
|
+
if value.is_integer():
|
|
27
|
+
return f"{int(value):,}"
|
|
28
|
+
|
|
29
|
+
if value != 0 and abs(value) < 0.01:
|
|
30
|
+
return f"{value:.4g}"
|
|
31
|
+
|
|
32
|
+
decimals = 2 if abs(value) >= 100 else 4
|
|
33
|
+
|
|
34
|
+
return f"{value:,.{decimals}f}".rstrip("0").rstrip(".")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _show(result, total, bin_pct, min_bin_n):
|
|
38
|
+
"""
|
|
39
|
+
Print a centred table: one line per bin with its range, count
|
|
40
|
+
and share. Every line is as wide as the widest content, so long
|
|
41
|
+
numbers widen the table instead of breaking it.
|
|
42
|
+
"""
|
|
43
|
+
sep = " "
|
|
44
|
+
pad = " "
|
|
45
|
+
ends = [(_fmt(lower), _fmt(upper)) for lower, upper, _ in result]
|
|
46
|
+
low_w = max(len(low) for low, _ in ends)
|
|
47
|
+
up_w = max(len(up) for _, up in ends)
|
|
48
|
+
|
|
49
|
+
ranges_text = [f"{low:>{low_w}} to {up:>{up_w}}" for low, up in ends]
|
|
50
|
+
counts = [f"{count:,}" for _, _, count in result]
|
|
51
|
+
shares = [f"{count / total * 100:.1f}%" for _, _, count in result]
|
|
52
|
+
numbers = [str(i) for i in range(1, len(result) + 1)]
|
|
53
|
+
|
|
54
|
+
widths = [
|
|
55
|
+
max(len("#"), len(numbers[-1])),
|
|
56
|
+
max(len("Range"), len(ranges_text[0]), len("Total")),
|
|
57
|
+
max(len("Count"), max(map(len, counts)), len(f"{total:,}")),
|
|
58
|
+
max(len("%"), max(map(len, shares)), len("100.0%")),
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
setting = f"bin_pct = {bin_pct:g}%"
|
|
62
|
+
|
|
63
|
+
settings_lines = [
|
|
64
|
+
setting,
|
|
65
|
+
f"min_bin_n = {min_bin_n} | {total:,} observations",
|
|
66
|
+
]
|
|
67
|
+
header_lines = [PY_NAME] + settings_lines
|
|
68
|
+
|
|
69
|
+
width = sum(widths) + len(sep) * 3 + len(pad) * 2
|
|
70
|
+
longest = max(len(line) for line in header_lines)
|
|
71
|
+
|
|
72
|
+
if longest > width:
|
|
73
|
+
widths[1] += longest - width
|
|
74
|
+
width = longest
|
|
75
|
+
|
|
76
|
+
def row(number, range_text, count, share):
|
|
77
|
+
return pad + sep.join([
|
|
78
|
+
number.rjust(widths[0]),
|
|
79
|
+
range_text.center(widths[1]),
|
|
80
|
+
count.rjust(widths[2]),
|
|
81
|
+
share.rjust(widths[3]),
|
|
82
|
+
]) + pad
|
|
83
|
+
|
|
84
|
+
rule = "-" * width
|
|
85
|
+
|
|
86
|
+
print()
|
|
87
|
+
|
|
88
|
+
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
title = PY_NAME.encode(encoding, "ignore").decode(encoding)
|
|
92
|
+
except LookupError:
|
|
93
|
+
title = PY_NAME
|
|
94
|
+
|
|
95
|
+
# Characters the terminal cannot show (an emoji, say) are dropped.
|
|
96
|
+
print(title.strip())
|
|
97
|
+
print()
|
|
98
|
+
|
|
99
|
+
for line in settings_lines:
|
|
100
|
+
print(line.center(width).rstrip())
|
|
101
|
+
|
|
102
|
+
print()
|
|
103
|
+
print(rule)
|
|
104
|
+
print(row("#", "Range", "Count", "%"))
|
|
105
|
+
print(rule)
|
|
106
|
+
|
|
107
|
+
for values in zip(numbers, ranges_text, counts, shares):
|
|
108
|
+
print(row(*values))
|
|
109
|
+
|
|
110
|
+
print(rule)
|
|
111
|
+
print(row("", "Total", f"{total:,}", "100.0%"))
|
|
112
|
+
print()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _empty_error():
|
|
116
|
+
return ValueError("values is empty.")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _distinct_with_counts(values):
|
|
120
|
+
"""
|
|
121
|
+
Return (distinct_values, counts), both sorted ascending, for the
|
|
122
|
+
observations in values. Validates that every value is a finite
|
|
123
|
+
real number.
|
|
124
|
+
|
|
125
|
+
Uses numpy (vectorised sort and unique) when it is installed and
|
|
126
|
+
the data is a plain numeric array; otherwise a pure-Python path
|
|
127
|
+
with the same results.
|
|
128
|
+
"""
|
|
129
|
+
if not hasattr(values, "__array__"):
|
|
130
|
+
values = list(values)
|
|
131
|
+
|
|
132
|
+
if _np is not None:
|
|
133
|
+
try:
|
|
134
|
+
arr = _np.asarray(values)
|
|
135
|
+
except (TypeError, ValueError):
|
|
136
|
+
arr = None
|
|
137
|
+
|
|
138
|
+
if arr is not None and arr.dtype.kind in "iuf":
|
|
139
|
+
if arr.size == 0:
|
|
140
|
+
raise _empty_error()
|
|
141
|
+
|
|
142
|
+
if arr.ndim != 1 or not _np.isfinite(arr).all():
|
|
143
|
+
raise ValueError("values must contain finite numeric values.")
|
|
144
|
+
|
|
145
|
+
distinct, counts = _np.unique(arr, return_counts=True)
|
|
146
|
+
|
|
147
|
+
return distinct.tolist(), counts.tolist()
|
|
148
|
+
|
|
149
|
+
ordered = list(values)
|
|
150
|
+
|
|
151
|
+
if not ordered:
|
|
152
|
+
raise _empty_error()
|
|
153
|
+
|
|
154
|
+
if not all(
|
|
155
|
+
isinstance(v, Real)
|
|
156
|
+
and not isinstance(v, _BOOL_TYPES)
|
|
157
|
+
and isfinite(v)
|
|
158
|
+
for v in ordered
|
|
159
|
+
):
|
|
160
|
+
raise ValueError("values must contain finite numeric values.")
|
|
161
|
+
|
|
162
|
+
ordered.sort()
|
|
163
|
+
|
|
164
|
+
distinct = []
|
|
165
|
+
counts = []
|
|
166
|
+
|
|
167
|
+
for value, group in groupby(ordered):
|
|
168
|
+
distinct.append(value)
|
|
169
|
+
counts.append(sum(1 for _ in group))
|
|
170
|
+
|
|
171
|
+
return distinct, counts
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def bin_edges(
|
|
175
|
+
values,
|
|
176
|
+
*,
|
|
177
|
+
ranges,
|
|
178
|
+
bin_pct=20,
|
|
179
|
+
min_bin_n=10,
|
|
180
|
+
display=True
|
|
181
|
+
):
|
|
182
|
+
"""
|
|
183
|
+
Generate population-based bin edges.
|
|
184
|
+
|
|
185
|
+
A bin is a slice of the population; its bin edges are the lower
|
|
186
|
+
and upper values that bound it. A range is a (lower, upper) pair
|
|
187
|
+
that can span one bin or several neighbouring bins.
|
|
188
|
+
|
|
189
|
+
Edges are observed values: each bin's lower and upper are the
|
|
190
|
+
smallest and largest values actually found in that bin. Gaps
|
|
191
|
+
between bins are therefore expected (bin 1 may end at 10 and
|
|
192
|
+
bin 2 start at 12 when no value lies between). The edges
|
|
193
|
+
describe the data passed in and are meant to be recalculated
|
|
194
|
+
whenever the data changes; they are not fixed thresholds for
|
|
195
|
+
classifying new, unseen values.
|
|
196
|
+
|
|
197
|
+
How bins are built: values are sorted and added to the current
|
|
198
|
+
bin until it reaches its target size, max(bin_pct percent of the
|
|
199
|
+
data, min_bin_n). Identical values are never split across bins,
|
|
200
|
+
so a bin can end up larger than its target, and a final bin left
|
|
201
|
+
below the target is merged into the previous one. A single bin
|
|
202
|
+
is allowed: when bin_pct or min_bin_n ask for as much as the
|
|
203
|
+
data holds, one bin carries all of it.
|
|
204
|
+
|
|
205
|
+
Parameters
|
|
206
|
+
----------
|
|
207
|
+
values : array-like
|
|
208
|
+
Numeric observations being split into bins. Every value must
|
|
209
|
+
be a finite real number (booleans are rejected).
|
|
210
|
+
Large inputs are handled with numpy when it is installed
|
|
211
|
+
(numeric arrays, lists and Series); other real numeric types,
|
|
212
|
+
such as Fraction, use a pure-Python path.
|
|
213
|
+
|
|
214
|
+
ranges : bool
|
|
215
|
+
Required, keyword-only.
|
|
216
|
+
True : Return every possible (lower, upper) range that can be
|
|
217
|
+
built from the bins: a range starts at the lower
|
|
218
|
+
edge of one bin and ends at the upper edge of the
|
|
219
|
+
same or a later bin, so k bins give
|
|
220
|
+
k * (k + 1) / 2 ranges. The base bins come first,
|
|
221
|
+
then the wider ranges grouped by start: every range
|
|
222
|
+
starting at bin 1 (ending at each later bin),
|
|
223
|
+
then those starting at bin 2, and so on to the end.
|
|
224
|
+
The output grows quickly with the number of bins
|
|
225
|
+
(5 bins give 15 ranges, 10 give 55, 100 give 5,050).
|
|
226
|
+
False : Return the bin boundaries as one sorted list: the
|
|
227
|
+
lower edge of every bin, followed by the upper edge
|
|
228
|
+
of the last bin. Each bin runs from its own value
|
|
229
|
+
up to, but not including, the next value in the list;
|
|
230
|
+
the last bin also includes its upper edge. For
|
|
231
|
+
example [1, 201, 401, 601, 999] describes the bins
|
|
232
|
+
1 to 200, 201 to 400, 401 to 600 and 601 to 999. If
|
|
233
|
+
the last bin holds a single repeated value, that
|
|
234
|
+
value appears twice at the end, so that bin keeps
|
|
235
|
+
its own interval.
|
|
236
|
+
|
|
237
|
+
bin_pct : float, default=20
|
|
238
|
+
Percentage of the population each bin should carry, between
|
|
239
|
+
0 and 100 (20 gives about 5 bins). It is a target: bins can
|
|
240
|
+
be larger, as described above.
|
|
241
|
+
|
|
242
|
+
min_bin_n : int, default=10
|
|
243
|
+
Minimum number of observations a bin should hold. The larger
|
|
244
|
+
of this and what bin_pct asks for is each bin's target. A bin
|
|
245
|
+
only holds fewer when the whole data has fewer than min_bin_n
|
|
246
|
+
observations, in which case one bin holds everything.
|
|
247
|
+
|
|
248
|
+
display : bool, default=True
|
|
249
|
+
True : Also print a small table with one row per bin (its
|
|
250
|
+
range, observation count and share of the population);
|
|
251
|
+
the combined ranges are not listed. The return value
|
|
252
|
+
is the same either way.
|
|
253
|
+
False : Print nothing.
|
|
254
|
+
|
|
255
|
+
Returns
|
|
256
|
+
-------
|
|
257
|
+
list
|
|
258
|
+
ranges=True : list of (lower, upper) tuples (see ranges).
|
|
259
|
+
ranges=False : sorted list of bin boundaries (see ranges).
|
|
260
|
+
|
|
261
|
+
Raises
|
|
262
|
+
------
|
|
263
|
+
ValueError
|
|
264
|
+
If an argument is invalid, or if values is empty or not
|
|
265
|
+
finite numbers.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
if not isinstance(ranges, _BOOL_TYPES):
|
|
269
|
+
raise ValueError(
|
|
270
|
+
"ranges must be True or False."
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
if not isinstance(display, _BOOL_TYPES):
|
|
274
|
+
raise ValueError(
|
|
275
|
+
"display must be True or False."
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
if (
|
|
279
|
+
not isinstance(bin_pct, Real)
|
|
280
|
+
or isinstance(bin_pct, _BOOL_TYPES)
|
|
281
|
+
or not isfinite(bin_pct)
|
|
282
|
+
or not 0 < bin_pct <= 100
|
|
283
|
+
):
|
|
284
|
+
raise ValueError(
|
|
285
|
+
"bin_pct must be a number between 0 and 100."
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
if (
|
|
289
|
+
not isinstance(min_bin_n, Integral)
|
|
290
|
+
or isinstance(min_bin_n, _BOOL_TYPES)
|
|
291
|
+
or min_bin_n < 1
|
|
292
|
+
):
|
|
293
|
+
raise ValueError(
|
|
294
|
+
"min_bin_n must be a whole number of at least 1."
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
min_bin_n = int(min_bin_n)
|
|
298
|
+
|
|
299
|
+
distinct, counts = _distinct_with_counts(values)
|
|
300
|
+
|
|
301
|
+
# cumulative[i] = observations in distinct[0..i]
|
|
302
|
+
cumulative = list(accumulate(counts))
|
|
303
|
+
total = cumulative[-1]
|
|
304
|
+
n_distinct = len(distinct)
|
|
305
|
+
|
|
306
|
+
# Population a bin needs before it is closed.
|
|
307
|
+
target = max(ceil(total * bin_pct / 100), min_bin_n)
|
|
308
|
+
|
|
309
|
+
result = []
|
|
310
|
+
start = 0 # first distinct value of the bin being filled
|
|
311
|
+
base = 0 # observations already placed in closed bins
|
|
312
|
+
|
|
313
|
+
# The loop runs once per bin, not once per value: a binary
|
|
314
|
+
# search on the cumulative counts finds where each bin closes.
|
|
315
|
+
while start < n_distinct:
|
|
316
|
+
stop = bisect_left(cumulative, base + target, start)
|
|
317
|
+
|
|
318
|
+
if stop >= n_distinct:
|
|
319
|
+
# Leftover values that never reached the target.
|
|
320
|
+
result.append([
|
|
321
|
+
distinct[start],
|
|
322
|
+
distinct[-1],
|
|
323
|
+
total - base
|
|
324
|
+
])
|
|
325
|
+
break
|
|
326
|
+
|
|
327
|
+
count = cumulative[stop] - base
|
|
328
|
+
|
|
329
|
+
result.append([
|
|
330
|
+
distinct[start],
|
|
331
|
+
distinct[stop],
|
|
332
|
+
count
|
|
333
|
+
])
|
|
334
|
+
|
|
335
|
+
base = cumulative[stop]
|
|
336
|
+
start = stop + 1
|
|
337
|
+
|
|
338
|
+
# Merge a final bin if it is below the target population.
|
|
339
|
+
if len(result) > 1 and result[-1][2] < target:
|
|
340
|
+
result[-2][1] = result[-1][1]
|
|
341
|
+
result[-2][2] += result[-1][2]
|
|
342
|
+
result.pop()
|
|
343
|
+
|
|
344
|
+
if ranges:
|
|
345
|
+
# Every continuous range the bins can form. The base bins
|
|
346
|
+
# come first, then the wider ranges grouped by start bin.
|
|
347
|
+
n_bins = len(result)
|
|
348
|
+
output = [
|
|
349
|
+
(lower, upper)
|
|
350
|
+
for lower, upper, count in result
|
|
351
|
+
]
|
|
352
|
+
output += [
|
|
353
|
+
(result[i][0], result[j][1])
|
|
354
|
+
for i in range(n_bins)
|
|
355
|
+
for j in range(i + 1, n_bins)
|
|
356
|
+
]
|
|
357
|
+
else:
|
|
358
|
+
# Boundaries: the lower edge of every bin, then the upper
|
|
359
|
+
# edge of the last bin.
|
|
360
|
+
output = [lower for lower, upper, count in result]
|
|
361
|
+
output.append(result[-1][1])
|
|
362
|
+
|
|
363
|
+
if display:
|
|
364
|
+
_show(result, total, bin_pct, min_bin_n)
|
|
365
|
+
|
|
366
|
+
return output
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quantile-edges
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Data-driven bin edges: bins are built from the data itself, not pre-set ranges, and each bin carries enough observations to be statistically reliable.
|
|
5
|
+
Requires-Python: >=3.8
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Provides-Extra: fast
|
|
8
|
+
Requires-Dist: numpy; extra == "fast"
|
|
9
|
+
Dynamic: description
|
|
10
|
+
Dynamic: description-content-type
|
|
11
|
+
Dynamic: provides-extra
|
|
12
|
+
Dynamic: requires-python
|
|
13
|
+
Dynamic: summary
|
|
14
|
+
|
|
15
|
+
# quantile-edges
|
|
16
|
+
|
|
17
|
+
**Data-driven bin edges that keep every bin statistically reliable.**
|
|
18
|
+
|
|
19
|
+
`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.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from quantile_edges import bin_edges
|
|
23
|
+
|
|
24
|
+
values = list(range(1, 101))
|
|
25
|
+
|
|
26
|
+
# 1. Bins of 25% each -> 4 bins, 10 ranges in total
|
|
27
|
+
bin_edges(values, ranges=True, bin_pct=25)
|
|
28
|
+
# [(1, 25), (26, 50), (51, 75), (76, 100),
|
|
29
|
+
# (1, 50), (1, 75), (1, 100),
|
|
30
|
+
# (26, 75), (26, 100),
|
|
31
|
+
# (51, 100)]
|
|
32
|
+
|
|
33
|
+
# 2. The same bins, returned as boundaries
|
|
34
|
+
bin_edges(values, ranges=False, bin_pct=25)
|
|
35
|
+
# [1, 26, 51, 76, 100]
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`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.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Purpose
|
|
43
|
+
|
|
44
|
+
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.
|
|
45
|
+
|
|
46
|
+
`quantile-edges` solves this at the source:
|
|
47
|
+
|
|
48
|
+
- **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.
|
|
49
|
+
- **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.
|
|
50
|
+
- **Identical values stay together.** Ties are never split across bins, so a value always belongs to exactly one bin.
|
|
51
|
+
|
|
52
|
+
This is useful for charts, scorecards, risk bands, cohort analysis and anywhere you group a numeric column before aggregating.
|
|
53
|
+
|
|
54
|
+
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.
|
|
55
|
+
|
|
56
|
+
**Two terms are used throughout:** a **bin** is a base slice of the population, and a **range** is a `(lower, upper)` pair that can span one bin or several neighbouring bins.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Parameters
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
bin_edges(
|
|
64
|
+
values,
|
|
65
|
+
*,
|
|
66
|
+
ranges,
|
|
67
|
+
bin_pct=20,
|
|
68
|
+
min_bin_n=10,
|
|
69
|
+
display=True,
|
|
70
|
+
)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
| Parameter | Type | Default | Meaning |
|
|
74
|
+
|---|---|---|---|
|
|
75
|
+
| `values` | array-like | required | Numeric observations (list, tuple, numpy array, pandas Series). Must be finite numbers; empty input raises. |
|
|
76
|
+
| `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. |
|
|
77
|
+
| `bin_pct` | number, `0 < x <= 100` | `20` | Share of the data each bin should carry. |
|
|
78
|
+
| `min_bin_n` | int, `>= 1` | `10` | Minimum observations in any bin. **Always enforced**: the larger of this and what `bin_pct` asks for wins. |
|
|
79
|
+
| `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. |
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## What you get back
|
|
84
|
+
|
|
85
|
+
### `ranges=True`: every range the bins can form
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
bin_edges(range(1, 101), ranges=True) # default bin_pct=20 -> 5 bins
|
|
91
|
+
# [(1, 20), (21, 40), (41, 60), (61, 80), (81, 100),
|
|
92
|
+
# (1, 40), (1, 60), (1, 80), (1, 100),
|
|
93
|
+
# (21, 60), (21, 80), (21, 100),
|
|
94
|
+
# (41, 80), (41, 100),
|
|
95
|
+
# (61, 100)]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
|
|
100
|
+
Every returned range contains at least `min_bin_n` observations, because each one includes at least one full bin.
|
|
101
|
+
|
|
102
|
+
**The output grows quickly with the number of bins.** `k` bins give `k * (k + 1) / 2` ranges:
|
|
103
|
+
|
|
104
|
+
| Bins | Ranges returned |
|
|
105
|
+
|---|---|
|
|
106
|
+
| 5 | 15 |
|
|
107
|
+
| 10 | 55 |
|
|
108
|
+
| 20 | 210 |
|
|
109
|
+
| 50 | 1,275 |
|
|
110
|
+
| 100 | 5,050 |
|
|
111
|
+
| 1,000 | 500,500 |
|
|
112
|
+
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
### `ranges=False`: the bin boundaries
|
|
116
|
+
|
|
117
|
+
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.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
bin_edges(range(1, 1000), ranges=False, bin_pct=20, display=False)
|
|
121
|
+
# [1, 201, 401, 601, 999]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
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).
|
|
125
|
+
|
|
126
|
+
If the last bin holds a single repeated value, that value appears twice at the end, so that bin keeps its own interval:
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
bin_edges([1]*10 + [2]*10, ranges=False, bin_pct=50, min_bin_n=5, display=False)
|
|
130
|
+
# [1, 2, 2]
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
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).
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## How it works
|
|
138
|
+
|
|
139
|
+
1. The values are sorted and grouped by distinct value.
|
|
140
|
+
2. Each bin's **target size** is set: `max(share, min_bin_n)`, where the share is `bin_pct` percent of all the data.
|
|
141
|
+
3. 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.
|
|
142
|
+
4. If the last bin is left below target, it is **merged into the previous one**.
|
|
143
|
+
5. The lowest and highest value actually found in each bin become its edges.
|
|
144
|
+
6. 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.
|
|
145
|
+
7. With `ranges=False`, the lower edge of every bin is returned, followed by the upper edge of the last bin.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## Examples
|
|
150
|
+
|
|
151
|
+
### Ties are never split
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
ties = [1]*30 + [2]*5 + [3]*25 + [4]*20 + [5]*20
|
|
155
|
+
|
|
156
|
+
bin_edges(ties, ranges=True, bin_pct=25, min_bin_n=10)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
Quantile_edges
|
|
161
|
+
|
|
162
|
+
bin_pct = 25%
|
|
163
|
+
min_bin_n = 10 | 100 observations
|
|
164
|
+
|
|
165
|
+
-----------------------------------
|
|
166
|
+
# Range Count %
|
|
167
|
+
-----------------------------------
|
|
168
|
+
1 1 to 1 30 30.0%
|
|
169
|
+
2 2 to 3 30 30.0%
|
|
170
|
+
3 4 to 5 40 40.0%
|
|
171
|
+
-----------------------------------
|
|
172
|
+
Total 100 100.0%
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
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.
|
|
176
|
+
|
|
177
|
+
### One bin carries everything
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
bin_edges(range(1, 21), ranges=True, min_bin_n=50, display=False)
|
|
181
|
+
# [(1, 20)]
|
|
182
|
+
|
|
183
|
+
bin_edges(range(1, 21), ranges=False, min_bin_n=50, display=False)
|
|
184
|
+
# [1, 20]
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
`min_bin_n=50` asks for more observations than the 20 available, so a single bin holds them all.
|
|
188
|
+
|
|
189
|
+
### A minimum bin size you can rely on
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
bin_edges(range(1, 101), ranges=True, bin_pct=5, min_bin_n=30, display=False)
|
|
193
|
+
# [(1, 30), (31, 60), (61, 100), (1, 60), (1, 100), (31, 100)]
|
|
194
|
+
# 5% bins were asked for, but no bin holds fewer than 30 rows
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
---
|
|
198
|
+
|
|
199
|
+
## Errors
|
|
200
|
+
|
|
201
|
+
All problems raise `ValueError` with a message that says how to fix it. Common ones:
|
|
202
|
+
|
|
203
|
+
| Situation | Message (shortened) |
|
|
204
|
+
|---|---|
|
|
205
|
+
| Empty input | `values is empty.` |
|
|
206
|
+
| NaN, infinity, text or booleans in `values` | `values must contain finite numeric values.` |
|
|
207
|
+
| `bin_pct` outside 0 to 100 | `bin_pct must be a number between 0 and 100.` |
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
quantile_edges/__init__.py,sha256=dvi3AM0bPn4-_PaO9oI1R0SpU6fP3XEJ9DI9faVRLXk,84
|
|
2
|
+
quantile_edges/quantile_edges.py,sha256=oyHHyfPzVWGCq6XBykdvSy4py20cPJgNh6nyiL0u63k,11453
|
|
3
|
+
quantile_edges-0.1.0.dist-info/METADATA,sha256=kHV2bqahV_ZIHu0FTfcpeQp5KIyNr1y89BMmuUjlDtg,8486
|
|
4
|
+
quantile_edges-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
quantile_edges-0.1.0.dist-info/top_level.txt,sha256=15kSZgc8yNyMqDVZxbAtTTNHC-HkJ2gvI80dsNDaCVI,15
|
|
6
|
+
quantile_edges-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quantile_edges
|