rfmkit 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.
- rfmkit/__init__.py +22 -0
- rfmkit/_utils.py +352 -0
- rfmkit/data/orders.csv +5001 -0
- rfmkit/datasets.py +36 -0
- rfmkit/plot.py +184 -0
- rfmkit/py.typed +0 -0
- rfmkit/segment.py +225 -0
- rfmkit/table.py +476 -0
- rfmkit-0.1.0.dist-info/METADATA +122 -0
- rfmkit-0.1.0.dist-info/RECORD +12 -0
- rfmkit-0.1.0.dist-info/WHEEL +4 -0
- rfmkit-0.1.0.dist-info/licenses/LICENSE +21 -0
rfmkit/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""rfmkit: recency, frequency and monetary analysis in pure pandas.
|
|
2
|
+
|
|
3
|
+
The public API keeps the R ``rfm`` 0.5.1 names so R and Python learners see
|
|
4
|
+
the same calls.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .datasets import load_orders
|
|
8
|
+
from .plot import rfm_plot_segment_summary
|
|
9
|
+
from .segment import rfm_segment, rfm_segment_summary
|
|
10
|
+
from .table import RFMTable, rfm_table_customer, rfm_table_order
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"RFMTable",
|
|
16
|
+
"load_orders",
|
|
17
|
+
"rfm_plot_segment_summary",
|
|
18
|
+
"rfm_segment",
|
|
19
|
+
"rfm_segment_summary",
|
|
20
|
+
"rfm_table_customer",
|
|
21
|
+
"rfm_table_order",
|
|
22
|
+
]
|
rfmkit/_utils.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""Internal validation and binning helpers for rfmkit.
|
|
2
|
+
|
|
3
|
+
The scoring rules here are a direct port of R ``rfm`` 0.5.1. In particular
|
|
4
|
+
the automatic cut points are type-7 sample quantiles and the interval index is
|
|
5
|
+
``findInterval()``: automatic bins are right-closed, custom breaks are
|
|
6
|
+
lower-inclusive. ``pandas.qcut`` is never used because it cannot represent the
|
|
7
|
+
empty bins that ties produce.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import datetime as _dt
|
|
13
|
+
import math
|
|
14
|
+
import numbers
|
|
15
|
+
import warnings
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
# Bin specifications
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def normalize_bins(value: Any, name: str) -> tuple[str, Any]:
|
|
28
|
+
"""Validate one ``*_bins`` argument.
|
|
29
|
+
|
|
30
|
+
A scalar means "this many automatic bins". A sequence of two or more
|
|
31
|
+
numbers means "these custom break points". A one-item sequence is
|
|
32
|
+
rejected because it cannot clearly mean either.
|
|
33
|
+
|
|
34
|
+
Returns
|
|
35
|
+
-------
|
|
36
|
+
(kind, spec)
|
|
37
|
+
``kind`` is ``"auto"`` or ``"custom"``; ``spec`` is an int for
|
|
38
|
+
automatic bins or a float64 array of break points for custom bins.
|
|
39
|
+
"""
|
|
40
|
+
if isinstance(value, (bool, np.bool_)):
|
|
41
|
+
raise TypeError(f"{name} must be a whole number >= 1 or a sequence of break points")
|
|
42
|
+
|
|
43
|
+
if isinstance(value, numbers.Integral):
|
|
44
|
+
n = int(value)
|
|
45
|
+
if n < 1:
|
|
46
|
+
raise ValueError(f"{name} must be a whole number >= 1")
|
|
47
|
+
return "auto", n
|
|
48
|
+
|
|
49
|
+
if isinstance(value, numbers.Real):
|
|
50
|
+
n = float(value)
|
|
51
|
+
if not math.isfinite(n) or n != math.floor(n) or n < 1:
|
|
52
|
+
raise ValueError(f"{name} must be a whole number >= 1")
|
|
53
|
+
return "auto", int(n)
|
|
54
|
+
|
|
55
|
+
if isinstance(value, (list, tuple, np.ndarray, pd.Series, pd.Index)):
|
|
56
|
+
items = list(value)
|
|
57
|
+
if len(items) == 0:
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"{name} must be a whole number >= 1 or a sequence of at least "
|
|
60
|
+
"2 break points"
|
|
61
|
+
)
|
|
62
|
+
if len(items) == 1:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
f"{name} cannot be a one-item sequence: use a whole number for "
|
|
65
|
+
"a bin count or at least 2 numbers for custom break points"
|
|
66
|
+
)
|
|
67
|
+
breaks: list[float] = []
|
|
68
|
+
for item in items:
|
|
69
|
+
if isinstance(item, (bool, np.bool_)) or not isinstance(item, numbers.Real):
|
|
70
|
+
raise TypeError(f"{name} break points must be numbers")
|
|
71
|
+
val = float(item)
|
|
72
|
+
if not math.isfinite(val):
|
|
73
|
+
raise ValueError(f"{name} break points must not contain NaN or infinity")
|
|
74
|
+
breaks.append(val)
|
|
75
|
+
arr = np.asarray(breaks, dtype=np.float64)
|
|
76
|
+
if np.any(np.diff(arr) < 0):
|
|
77
|
+
raise ValueError(f"{name} break points must be sorted in non-decreasing order")
|
|
78
|
+
return "custom", arr
|
|
79
|
+
|
|
80
|
+
raise TypeError(f"{name} must be a whole number >= 1 or a sequence of break points")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def keep_bins_as_given(value: Any) -> Any:
|
|
84
|
+
"""Return an input bin specification in a form that is safe to store."""
|
|
85
|
+
if isinstance(value, np.ndarray):
|
|
86
|
+
return value.tolist()
|
|
87
|
+
if isinstance(value, pd.Series):
|
|
88
|
+
return value.tolist()
|
|
89
|
+
if isinstance(value, np.generic):
|
|
90
|
+
return value.item()
|
|
91
|
+
return value
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
# Dates
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def as_analysis_date(value: Any) -> pd.Timestamp:
|
|
100
|
+
"""Validate ``analysis_date`` and return a normalised ``Timestamp``.
|
|
101
|
+
|
|
102
|
+
R accepts only a ``Date``; a character date fails inside ``-.Date``. The
|
|
103
|
+
same rule is kept: text is an error, named after the argument.
|
|
104
|
+
"""
|
|
105
|
+
if value is None:
|
|
106
|
+
raise TypeError("analysis_date must be a date, not None")
|
|
107
|
+
if isinstance(value, (str, bytes)):
|
|
108
|
+
raise TypeError(
|
|
109
|
+
"analysis_date must be a date (datetime.date, datetime.datetime, "
|
|
110
|
+
"pandas.Timestamp or numpy.datetime64), not a string"
|
|
111
|
+
)
|
|
112
|
+
if isinstance(value, pd.Timestamp):
|
|
113
|
+
ts = value
|
|
114
|
+
elif isinstance(value, np.datetime64):
|
|
115
|
+
ts = pd.Timestamp(value)
|
|
116
|
+
elif isinstance(value, (_dt.datetime, _dt.date)):
|
|
117
|
+
ts = pd.Timestamp(value)
|
|
118
|
+
else:
|
|
119
|
+
raise TypeError(
|
|
120
|
+
"analysis_date must be a date (datetime.date, datetime.datetime, "
|
|
121
|
+
"pandas.Timestamp or numpy.datetime64)"
|
|
122
|
+
)
|
|
123
|
+
if pd.isna(ts):
|
|
124
|
+
raise ValueError("analysis_date must not be NaT")
|
|
125
|
+
if ts.tzinfo is not None:
|
|
126
|
+
raise TypeError("analysis_date must be timezone-naive")
|
|
127
|
+
return ts.normalize()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _is_date_object(value: Any) -> bool:
|
|
131
|
+
return isinstance(value, (_dt.date, _dt.datetime, np.datetime64, pd.Timestamp))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def date_column(series: pd.Series, name: str) -> pd.Series:
|
|
135
|
+
"""Validate a date column and return a normalised datetime Series.
|
|
136
|
+
|
|
137
|
+
A timezone-aware column or a column with a time-of-day component is
|
|
138
|
+
rejected. R silently computes nonsense for a ``POSIXct`` column; rfmkit
|
|
139
|
+
raises a ``TypeError`` that names the argument instead (API difference Q6).
|
|
140
|
+
"""
|
|
141
|
+
if isinstance(series.dtype, pd.DatetimeTZDtype):
|
|
142
|
+
raise TypeError(f"{name} must be a date column without a timezone")
|
|
143
|
+
if not pd.api.types.is_datetime64_any_dtype(series.dtype):
|
|
144
|
+
non_null = series.dropna()
|
|
145
|
+
if len(non_null) == 0:
|
|
146
|
+
return pd.to_datetime(series, errors="coerce").dt.normalize()
|
|
147
|
+
if not all(_is_date_object(v) for v in non_null):
|
|
148
|
+
raise TypeError(
|
|
149
|
+
f"{name} must be a date column (datetime64 or datetime.date values)"
|
|
150
|
+
)
|
|
151
|
+
converted = pd.to_datetime(series, errors="coerce")
|
|
152
|
+
if converted.isna().sum() < series.isna().sum():
|
|
153
|
+
raise TypeError(
|
|
154
|
+
f"{name} must be a date column (datetime64 or datetime.date values)"
|
|
155
|
+
)
|
|
156
|
+
else:
|
|
157
|
+
converted = pd.to_datetime(series, errors="coerce")
|
|
158
|
+
|
|
159
|
+
non_null_converted = converted.dropna()
|
|
160
|
+
if len(non_null_converted) > 0:
|
|
161
|
+
if (non_null_converted != non_null_converted.dt.normalize()).any():
|
|
162
|
+
raise TypeError(
|
|
163
|
+
f"{name} must be a date column without a time component; "
|
|
164
|
+
"got a date-time column"
|
|
165
|
+
)
|
|
166
|
+
return converted.dt.normalize()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def days_between(analysis_date: pd.Timestamp, dates: pd.Series) -> pd.Series:
|
|
170
|
+
"""Calendar-day difference as float days, with NaT becoming NaN."""
|
|
171
|
+
delta = analysis_date - dates
|
|
172
|
+
return delta.dt.total_seconds() / 86400.0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------------------
|
|
176
|
+
# Numeric input checks
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def require_numeric(series: pd.Series, name: str) -> None:
|
|
181
|
+
"""Raise a ``TypeError`` naming ``name`` when a column is not numeric."""
|
|
182
|
+
if pd.api.types.is_bool_dtype(series.dtype) or not pd.api.types.is_numeric_dtype(
|
|
183
|
+
series.dtype
|
|
184
|
+
):
|
|
185
|
+
raise TypeError(f"{name} must be a numeric column")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def integer_counts(series: pd.Series, name: str) -> pd.Series:
|
|
189
|
+
"""Validate a count column and return int64 (API difference Q15/Q16).
|
|
190
|
+
|
|
191
|
+
Fractional values fail up front with a message naming the argument. Null
|
|
192
|
+
values are preserved as a nullable ``Int64`` column so that ``NA`` behaves
|
|
193
|
+
like R; every other value is checked against the int64 range.
|
|
194
|
+
"""
|
|
195
|
+
require_numeric(series, name)
|
|
196
|
+
values = series.to_numpy(dtype=float, na_value=np.nan)
|
|
197
|
+
non_null = values[~np.isnan(values)]
|
|
198
|
+
if np.any(non_null != np.floor(non_null)):
|
|
199
|
+
raise ValueError(f"{name} must contain whole numbers (transaction counts)")
|
|
200
|
+
limit = np.iinfo(np.int64)
|
|
201
|
+
if pd.api.types.is_integer_dtype(series.dtype):
|
|
202
|
+
if any(int(v) > limit.max or int(v) < limit.min for v in series.dropna()):
|
|
203
|
+
raise ValueError(f"{name} values must fit in a 64-bit integer")
|
|
204
|
+
else:
|
|
205
|
+
if np.any(non_null >= 2.0**63) or np.any(non_null < -(2.0**63)):
|
|
206
|
+
raise ValueError(f"{name} values must fit in a 64-bit integer")
|
|
207
|
+
if np.isnan(values).any():
|
|
208
|
+
return pd.Series(pd.array(values, dtype="Int64"), index=series.index)
|
|
209
|
+
return pd.Series(values.astype(np.int64), index=series.index)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# ---------------------------------------------------------------------------
|
|
213
|
+
# Rounding
|
|
214
|
+
# ---------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def r_round2(values: Any) -> np.ndarray:
|
|
218
|
+
"""Round to two decimals exactly as R 4.x ``round(x, 2)``.
|
|
219
|
+
|
|
220
|
+
R picks the nearer of the two representable two-decimal candidates; on an
|
|
221
|
+
exact tie it takes the upper candidate when the scaled integer is odd and
|
|
222
|
+
the lower one otherwise. The arithmetic is deliberately done in binary
|
|
223
|
+
doubles, exactly as R's ``fround()`` does, so values such as ``133.975``
|
|
224
|
+
land where R puts them. This is neither numpy/pandas ``round`` nor
|
|
225
|
+
Python's built-in ``round``; both disagree with R on values such as
|
|
226
|
+
``2.675`` and ``1.115``. NaN and +/-inf pass through unchanged.
|
|
227
|
+
"""
|
|
228
|
+
arr = np.asarray(values, dtype=np.float64)
|
|
229
|
+
flat = arr.reshape(-1)
|
|
230
|
+
out = flat.copy()
|
|
231
|
+
for index in np.flatnonzero(np.isfinite(flat)):
|
|
232
|
+
out[index] = _r_round2_scalar(float(flat[index]))
|
|
233
|
+
return out.reshape(arr.shape)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _r_round2_scalar(value: float) -> float:
|
|
237
|
+
"""The scalar R ``fround(value, 2)`` step used by :func:`r_round2`."""
|
|
238
|
+
sign = -1.0 if value < 0.0 else 1.0
|
|
239
|
+
x = abs(value)
|
|
240
|
+
scaled = x * 100.0
|
|
241
|
+
lower_index = math.floor(scaled)
|
|
242
|
+
lower = lower_index / 100.0
|
|
243
|
+
upper = math.ceil(scaled) / 100.0
|
|
244
|
+
du = upper - x
|
|
245
|
+
dd = x - lower
|
|
246
|
+
if du < dd or (math.fmod(lower_index, 2.0) == 1.0 and du == dd):
|
|
247
|
+
return sign * upper
|
|
248
|
+
return sign * lower
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# ---------------------------------------------------------------------------
|
|
252
|
+
# Binning
|
|
253
|
+
# ---------------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def quantile_breaks(values: np.ndarray, n_bins: int) -> np.ndarray:
|
|
257
|
+
"""Type-7 sample quantiles at ``k / n_bins`` (R ``quantile()`` default)."""
|
|
258
|
+
probs = np.arange(1, n_bins, dtype=np.float64) / n_bins
|
|
259
|
+
return np.quantile(values, probs, method="linear")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def bin_index(
|
|
263
|
+
values: np.ndarray,
|
|
264
|
+
breaks: np.ndarray,
|
|
265
|
+
automatic: bool,
|
|
266
|
+
column: str,
|
|
267
|
+
) -> np.ndarray:
|
|
268
|
+
"""R ``findInterval()`` index (0-based interval number).
|
|
269
|
+
|
|
270
|
+
Automatic bins use ``side="left"`` (right-closed intervals, a value on a
|
|
271
|
+
cut point stays low). Custom bins use ``side="right"`` (lower-inclusive,
|
|
272
|
+
a value on a break enters the next interval). NaN is masked to NaN so the
|
|
273
|
+
caller can produce an ``NA`` score, as R does with custom breaks.
|
|
274
|
+
"""
|
|
275
|
+
arr = np.asarray(values, dtype=np.float64)
|
|
276
|
+
if automatic and np.isnan(arr).any():
|
|
277
|
+
raise ValueError(
|
|
278
|
+
f"missing values and NaN's are not allowed in {column} when "
|
|
279
|
+
"automatic bins are used (na.rm is FALSE in R)"
|
|
280
|
+
)
|
|
281
|
+
if automatic:
|
|
282
|
+
return np.searchsorted(breaks, arr, side="left").astype(np.float64)
|
|
283
|
+
idx = np.searchsorted(breaks, arr, side="right").astype(np.float64)
|
|
284
|
+
idx[np.isnan(arr)] = np.nan
|
|
285
|
+
return idx
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def dimension_breaks(
|
|
289
|
+
values: pd.Series,
|
|
290
|
+
spec: tuple[str, Any],
|
|
291
|
+
) -> tuple[np.ndarray, int, bool]:
|
|
292
|
+
"""Return ``(breaks, n_intervals, automatic)`` for one dimension."""
|
|
293
|
+
kind, detail = spec
|
|
294
|
+
automatic = kind == "auto"
|
|
295
|
+
arr = values.to_numpy(dtype=np.float64, na_value=np.nan)
|
|
296
|
+
if automatic:
|
|
297
|
+
if np.isnan(arr).any():
|
|
298
|
+
# Let bin_index raise the same, consistent message.
|
|
299
|
+
return np.asarray([], dtype=np.float64), int(detail), True
|
|
300
|
+
breaks = quantile_breaks(arr, int(detail))
|
|
301
|
+
return breaks, int(detail), True
|
|
302
|
+
breaks = np.asarray(detail, dtype=np.float64)
|
|
303
|
+
return breaks, len(breaks) + 1, False
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def threshold_bounds(
|
|
307
|
+
values: pd.Series,
|
|
308
|
+
breaks: np.ndarray,
|
|
309
|
+
automatic: bool,
|
|
310
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
311
|
+
"""Build the display-only lower/upper bounds, exactly as R does."""
|
|
312
|
+
if len(values) == 0:
|
|
313
|
+
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
|
|
314
|
+
arr = values.to_numpy(dtype=np.float64, na_value=np.nan)
|
|
315
|
+
if len(arr) == 0:
|
|
316
|
+
return np.asarray([], dtype=np.float64), np.asarray([], dtype=np.float64)
|
|
317
|
+
lower_min = np.min(arr)
|
|
318
|
+
upper_max = np.max(arr)
|
|
319
|
+
if automatic:
|
|
320
|
+
lower = np.concatenate(([lower_min], breaks))
|
|
321
|
+
upper = np.concatenate((breaks, [upper_max]))
|
|
322
|
+
else:
|
|
323
|
+
lower = np.concatenate(([lower_min], breaks))
|
|
324
|
+
upper = np.concatenate((breaks, [upper_max + 1.0]))
|
|
325
|
+
return lower, upper
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def pad_arrays(arrays: list[np.ndarray]) -> list[np.ndarray]:
|
|
329
|
+
"""NaN-pad threshold arrays to the longest dimension (R #113)."""
|
|
330
|
+
n = max((len(a) for a in arrays), default=0)
|
|
331
|
+
padded: list[np.ndarray] = []
|
|
332
|
+
for arr in arrays:
|
|
333
|
+
arr = np.asarray(arr, dtype=np.float64)
|
|
334
|
+
if len(arr) < n:
|
|
335
|
+
arr = np.concatenate((arr, np.full(n - len(arr), np.nan)))
|
|
336
|
+
padded.append(arr)
|
|
337
|
+
return padded
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
# ---------------------------------------------------------------------------
|
|
341
|
+
# Warnings
|
|
342
|
+
# ---------------------------------------------------------------------------
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def warn_dropped_metadata(columns: list[str]) -> None:
|
|
346
|
+
"""Emit the same message R emits for varying metadata columns."""
|
|
347
|
+
if columns:
|
|
348
|
+
warnings.warn(
|
|
349
|
+
"Dropping columns that vary within a customer: " + ", ".join(columns),
|
|
350
|
+
UserWarning,
|
|
351
|
+
stacklevel=3,
|
|
352
|
+
)
|