openretailscience 0.45.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.
- openretailscience/__init__.py +3 -0
- openretailscience/analysis/__init__.py +0 -0
- openretailscience/analysis/cohort.py +185 -0
- openretailscience/analysis/composite_rank.py +372 -0
- openretailscience/analysis/cross_shop.py +354 -0
- openretailscience/analysis/customer.py +459 -0
- openretailscience/analysis/customer_decision_hierarchy.py +359 -0
- openretailscience/analysis/gain_loss.py +340 -0
- openretailscience/analysis/haversine.py +50 -0
- openretailscience/analysis/product_association.py +418 -0
- openretailscience/analysis/revenue_tree.py +553 -0
- openretailscience/assets/fonts/Poppins-Bold.ttf +0 -0
- openretailscience/assets/fonts/Poppins-LightItalic.ttf +0 -0
- openretailscience/assets/fonts/Poppins-Medium.ttf +0 -0
- openretailscience/assets/fonts/Poppins-Regular.ttf +0 -0
- openretailscience/assets/fonts/Poppins-SemiBold.ttf +0 -0
- openretailscience/constants.py +295 -0
- openretailscience/metrics/__init__.py +0 -0
- openretailscience/metrics/base.py +29 -0
- openretailscience/metrics/distribution/__init__.py +0 -0
- openretailscience/metrics/distribution/acv.py +81 -0
- openretailscience/metrics/distribution/pct_of_stores.py +118 -0
- openretailscience/options.py +842 -0
- openretailscience/plots/__init__.py +0 -0
- openretailscience/plots/area.py +114 -0
- openretailscience/plots/bar.py +375 -0
- openretailscience/plots/broken_timeline.py +197 -0
- openretailscience/plots/cohort.py +94 -0
- openretailscience/plots/heatmap.py +134 -0
- openretailscience/plots/histogram.py +276 -0
- openretailscience/plots/index.py +505 -0
- openretailscience/plots/line.py +379 -0
- openretailscience/plots/period_on_period.py +144 -0
- openretailscience/plots/price.py +275 -0
- openretailscience/plots/scatter.py +382 -0
- openretailscience/plots/styles/__init__.py +1 -0
- openretailscience/plots/styles/colors.py +215 -0
- openretailscience/plots/styles/font_utils.py +62 -0
- openretailscience/plots/styles/graph_utils.py +834 -0
- openretailscience/plots/styles/styling_helpers.py +155 -0
- openretailscience/plots/time.py +160 -0
- openretailscience/plots/tree_diagram.py +813 -0
- openretailscience/plots/venn.py +127 -0
- openretailscience/plots/waterfall.py +217 -0
- openretailscience/plugin.py +238 -0
- openretailscience/segmentation/__init__.py +0 -0
- openretailscience/segmentation/hml.py +97 -0
- openretailscience/segmentation/nlr.py +218 -0
- openretailscience/segmentation/rfm.py +307 -0
- openretailscience/segmentation/segstats.py +1177 -0
- openretailscience/segmentation/threshold.py +165 -0
- openretailscience/utils/__init__.py +0 -0
- openretailscience/utils/date.py +226 -0
- openretailscience/utils/filter_and_label.py +52 -0
- openretailscience/utils/label.py +79 -0
- openretailscience/utils/validation.py +45 -0
- openretailscience-0.45.0.dist-info/METADATA +364 -0
- openretailscience-0.45.0.dist-info/RECORD +60 -0
- openretailscience-0.45.0.dist-info/WHEEL +4 -0
- openretailscience-0.45.0.dist-info/licenses/LICENSE +93 -0
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""Customer Purchase Behavior Analysis for Retention and Value Optimization.
|
|
2
|
+
|
|
3
|
+
## Business Context
|
|
4
|
+
|
|
5
|
+
Understanding customer purchase patterns is fundamental to retail success. Some customers
|
|
6
|
+
make single purchases and never return, while others become loyal repeat buyers. This
|
|
7
|
+
module analyzes the distribution of purchase frequency to identify customer behavior
|
|
8
|
+
segments and inform retention strategies.
|
|
9
|
+
|
|
10
|
+
## The Business Problem
|
|
11
|
+
|
|
12
|
+
Retailers need to understand the relationship between customer purchase frequency and
|
|
13
|
+
business performance:
|
|
14
|
+
- What percentage of customers are one-time buyers versus repeat customers?
|
|
15
|
+
- How does purchase frequency relate to customer lifetime value?
|
|
16
|
+
- Which customer segments offer the greatest growth opportunities?
|
|
17
|
+
|
|
18
|
+
Without this analysis, businesses may invest equally in all customers or fail to
|
|
19
|
+
identify high-potential segments for targeted retention efforts.
|
|
20
|
+
|
|
21
|
+
## Real-World Applications
|
|
22
|
+
|
|
23
|
+
### Customer Retention Strategy
|
|
24
|
+
- Identify the percentage of one-time buyers for targeted reactivation campaigns
|
|
25
|
+
- Segment customers by purchase frequency for differentiated marketing approaches
|
|
26
|
+
- Develop loyalty programs based on actual behavior patterns
|
|
27
|
+
|
|
28
|
+
### Resource Allocation
|
|
29
|
+
- Focus retention efforts on customers showing repeat purchase potential
|
|
30
|
+
- Allocate customer service resources based on customer value segments
|
|
31
|
+
- Optimize marketing spend by targeting high-frequency customer characteristics
|
|
32
|
+
|
|
33
|
+
### Business Performance Monitoring
|
|
34
|
+
- Track changes in purchase frequency distribution over time
|
|
35
|
+
- Monitor the health of customer acquisition versus retention balance
|
|
36
|
+
- Identify shifts in customer behavior that may indicate market changes
|
|
37
|
+
|
|
38
|
+
This module visualizes purchase frequency distribution to reveal customer behavior
|
|
39
|
+
patterns and guide strategic retention decisions.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
import operator
|
|
43
|
+
|
|
44
|
+
import matplotlib.ticker as mtick
|
|
45
|
+
import pandas as pd
|
|
46
|
+
from matplotlib.axes import Axes, SubplotBase
|
|
47
|
+
|
|
48
|
+
import openretailscience.plots.styles.graph_utils as gu
|
|
49
|
+
from openretailscience.options import ColumnHelper
|
|
50
|
+
from openretailscience.plots.styles.colors import COLORS
|
|
51
|
+
from openretailscience.plots.styles.graph_utils import human_format, standard_graph_styles
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class PurchasesPerCustomer:
|
|
55
|
+
"""A class to plot the distribution of the number of purchases per customer.
|
|
56
|
+
|
|
57
|
+
Attributes:
|
|
58
|
+
cust_purchases_s (pd.Series): The number of purchases per customer.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, df: pd.DataFrame) -> None:
|
|
62
|
+
"""Initialize the PurchasesPerCustomer class.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
df (pd.DataFrame): A dataframe with the transaction data. The dataframe must comply with the
|
|
66
|
+
contain customer_id and transaction_id columns, which must be non-null.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
ValueError: If the dataframe doesn't contain the columns customer_id and transaction_id, or if the columns
|
|
70
|
+
are null.
|
|
71
|
+
|
|
72
|
+
"""
|
|
73
|
+
cols = ColumnHelper()
|
|
74
|
+
required_cols = [cols.customer_id, cols.transaction_id]
|
|
75
|
+
missing_cols = set(required_cols) - set(df.columns)
|
|
76
|
+
if len(missing_cols) > 0:
|
|
77
|
+
msg = f"The following columns are required but missing: {missing_cols}"
|
|
78
|
+
raise ValueError(msg)
|
|
79
|
+
|
|
80
|
+
self.cust_purchases_s = df.groupby(cols.customer_id)[cols.transaction_id].nunique()
|
|
81
|
+
|
|
82
|
+
def plot(
|
|
83
|
+
self,
|
|
84
|
+
bins: int = 10,
|
|
85
|
+
cumulative: bool = False,
|
|
86
|
+
ax: Axes | None = None,
|
|
87
|
+
percentile_line: float | None = None,
|
|
88
|
+
source_text: str | None = None,
|
|
89
|
+
title: str | None = None,
|
|
90
|
+
x_label: str | None = None,
|
|
91
|
+
y_label: str | None = None,
|
|
92
|
+
**kwargs: dict[str, any],
|
|
93
|
+
) -> SubplotBase:
|
|
94
|
+
"""Plot the distribution of the number of purchases per customer.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
bins (int, optional): The number of bins to plot. Defaults to 10.
|
|
98
|
+
cumulative (bool, optional): Whether to plot the cumulative distribution. Defaults to False.
|
|
99
|
+
ax (Axes, optional): The Matplotlib axes to plot the graph on. Defaults to None.
|
|
100
|
+
percentile_line (float, optional): The percentile to draw a line at. Defaults to None. When None then no
|
|
101
|
+
line is drawn.
|
|
102
|
+
source_text (str, optional): The source text to add to the plot. Defaults to None.
|
|
103
|
+
title (str, optional): The title of the plot. Defaults to None.
|
|
104
|
+
x_label (str, optional): The x-axis label. Defaults to None.
|
|
105
|
+
y_label (str, optional): The y-axis label. Defaults to None.
|
|
106
|
+
kwargs (dict[str, any]): Additional keyword arguments to pass to the plot function.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
SubplotBase: The Matplotlib axes of the plot
|
|
110
|
+
"""
|
|
111
|
+
density = False
|
|
112
|
+
if cumulative:
|
|
113
|
+
density = True
|
|
114
|
+
|
|
115
|
+
if x_label is None:
|
|
116
|
+
x_label = "Number of purchases"
|
|
117
|
+
|
|
118
|
+
ax = self.cust_purchases_s.hist(
|
|
119
|
+
bins=bins,
|
|
120
|
+
cumulative=cumulative,
|
|
121
|
+
ax=ax,
|
|
122
|
+
density=density,
|
|
123
|
+
color=COLORS["green"][500],
|
|
124
|
+
**kwargs,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
ax.xaxis.set_major_formatter(lambda x, pos: human_format(x, pos, decimals=0))
|
|
128
|
+
|
|
129
|
+
if cumulative:
|
|
130
|
+
default_title = "Number of Purchases cumulative Distribution"
|
|
131
|
+
default_y_label = "Percentage of customers"
|
|
132
|
+
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
|
|
133
|
+
|
|
134
|
+
else:
|
|
135
|
+
default_title = "Number of Purchases Distribution"
|
|
136
|
+
default_y_label = "Number of customers"
|
|
137
|
+
ax.yaxis.set_major_formatter(lambda x, pos: human_format(x, pos, decimals=0))
|
|
138
|
+
|
|
139
|
+
ax = standard_graph_styles(
|
|
140
|
+
ax,
|
|
141
|
+
title=gu.not_none(title, default_title),
|
|
142
|
+
x_label=x_label,
|
|
143
|
+
y_label=gu.not_none(y_label, default_y_label),
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
if percentile_line is not None:
|
|
147
|
+
if percentile_line > 1 or percentile_line < 0:
|
|
148
|
+
raise ValueError("Percentile line must be between 0 and 1")
|
|
149
|
+
ax.axvline(
|
|
150
|
+
x=self.purchases_percentile(percentile_line),
|
|
151
|
+
color=COLORS["red"][500],
|
|
152
|
+
linestyle="--",
|
|
153
|
+
lw=2,
|
|
154
|
+
label=f"{percentile_line:.1%} of customers",
|
|
155
|
+
)
|
|
156
|
+
ax.legend(frameon=False)
|
|
157
|
+
|
|
158
|
+
if source_text:
|
|
159
|
+
gu.add_source_text(ax=ax, source_text=source_text)
|
|
160
|
+
|
|
161
|
+
return ax
|
|
162
|
+
|
|
163
|
+
def purchases_percentile(self, percentile: float = 0.5) -> float:
|
|
164
|
+
"""Get the number of purchases at a given percentile.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
percentile (float): The percentile to get the number of purchases at.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
float: The number of purchases at the given percentile.
|
|
171
|
+
"""
|
|
172
|
+
return self.cust_purchases_s.quantile(percentile)
|
|
173
|
+
|
|
174
|
+
def find_purchase_percentile(self, number_of_purchases: int, comparison: str = "less_than_equal_to") -> float:
|
|
175
|
+
"""Find the percentile of the number of purchases.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
number_of_purchases (int): The number of purchases to find the percentile of.
|
|
179
|
+
comparison (str, optional): The comparison to use. Defaults to "less_than_equal_to". Must be one of
|
|
180
|
+
less_than, less_than_equal_to, equal_to, not_equal_to, greater_than, or greater_than_equal_to.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
float: The percentile of the number of purchases.
|
|
184
|
+
"""
|
|
185
|
+
ops = {
|
|
186
|
+
"less_than": operator.lt,
|
|
187
|
+
"less_than_equal_to": operator.le,
|
|
188
|
+
"equal_to": operator.eq,
|
|
189
|
+
"not_equal_to": operator.ne,
|
|
190
|
+
"greater_than": operator.gt,
|
|
191
|
+
"greater_than_equal_to": operator.ge,
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if comparison not in ops:
|
|
195
|
+
msg = f"Comparison must be one of {', '.join(repr(k) for k in ops)}"
|
|
196
|
+
raise ValueError(msg)
|
|
197
|
+
|
|
198
|
+
return len(self.cust_purchases_s[ops[comparison](self.cust_purchases_s, number_of_purchases)]) / len(
|
|
199
|
+
self.cust_purchases_s,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class DaysBetweenPurchases:
|
|
204
|
+
"""A class to plot the distribution of the average number of days between purchases per customer.
|
|
205
|
+
|
|
206
|
+
Attributes:
|
|
207
|
+
purchase_dist_s (pd.Series): The average number of days between purchases per customer.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
def __init__(self, df: pd.DataFrame) -> None:
|
|
211
|
+
"""Initialize the DaysBetweenPurchases class.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
df (pd.DataFrame): A dataframe with the transaction data. The dataframe must have the columns customer_id
|
|
215
|
+
and transaction_date, which must be non-null.
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
ValueError: If the dataframe does doesn't contain the columns customer_id and transaction_id, or if the
|
|
219
|
+
columns are null.
|
|
220
|
+
|
|
221
|
+
"""
|
|
222
|
+
cols = ColumnHelper()
|
|
223
|
+
required_cols = [cols.customer_id, cols.transaction_date]
|
|
224
|
+
missing_cols = set(required_cols) - set(df.columns)
|
|
225
|
+
if len(missing_cols) > 0:
|
|
226
|
+
msg = f"The following columns are required but missing: {missing_cols}"
|
|
227
|
+
raise ValueError(msg)
|
|
228
|
+
|
|
229
|
+
self.purchase_dist_s = self._calculate_days_between_purchases(df)
|
|
230
|
+
|
|
231
|
+
@staticmethod
|
|
232
|
+
def _calculate_days_between_purchases(df: pd.DataFrame) -> pd.Series:
|
|
233
|
+
"""Calculate the average number of days between purchases per customer.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
df (pd.DataFrame): A dataframe with the transaction data. The dataframe must have the columns customer_id
|
|
237
|
+
and transaction_date, which must be non-null.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
pd.Series: The average number of days between purchases per customer.
|
|
241
|
+
"""
|
|
242
|
+
cols = ColumnHelper()
|
|
243
|
+
required_cols = [cols.customer_id, cols.transaction_date]
|
|
244
|
+
missing_cols = set(required_cols) - set(df.columns)
|
|
245
|
+
if len(missing_cols) > 0:
|
|
246
|
+
msg = f"The following columns are required but missing: {missing_cols}"
|
|
247
|
+
raise ValueError(msg)
|
|
248
|
+
|
|
249
|
+
purchase_dist_df = df[[cols.customer_id, cols.transaction_date]].copy()
|
|
250
|
+
purchase_dist_df[cols.transaction_date] = df[cols.transaction_date].dt.floor("D")
|
|
251
|
+
purchase_dist_df = purchase_dist_df.drop_duplicates().sort_values([cols.customer_id, cols.transaction_date])
|
|
252
|
+
purchase_dist_df["diff"] = purchase_dist_df[cols.transaction_date].diff()
|
|
253
|
+
new_cust_mask = purchase_dist_df[cols.customer_id] != purchase_dist_df[cols.customer_id].shift(1)
|
|
254
|
+
purchase_dist_df = purchase_dist_df[~new_cust_mask]
|
|
255
|
+
purchase_dist_df["diff"] = purchase_dist_df["diff"].dt.days
|
|
256
|
+
return purchase_dist_df.groupby(cols.customer_id)["diff"].mean()
|
|
257
|
+
|
|
258
|
+
def plot(
|
|
259
|
+
self,
|
|
260
|
+
bins: int = 10,
|
|
261
|
+
cumulative: bool = False,
|
|
262
|
+
ax: Axes | None = None,
|
|
263
|
+
percentile_line: float | None = None,
|
|
264
|
+
title: str | None = None,
|
|
265
|
+
x_label: str | None = None,
|
|
266
|
+
y_label: str | None = None,
|
|
267
|
+
source_text: str | None = None,
|
|
268
|
+
**kwargs: dict[str, any],
|
|
269
|
+
) -> SubplotBase:
|
|
270
|
+
"""Plot the distribution of the average number of days between purchases per customer.
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
bins (int, optional): The number of bins to plot. Defaults to 10.
|
|
274
|
+
cumulative (bool, optional): Whether to plot the cumulative distribution. Defaults to False.
|
|
275
|
+
ax (Axes, optional): The Matplotlib axes to plot the graph on. Defaults to None.
|
|
276
|
+
percentile_line (float, optional): The percentile to draw a line at. Defaults to None. When None then no
|
|
277
|
+
line is drawn.
|
|
278
|
+
title (str, optional): The title of the plot. Defaults to None.
|
|
279
|
+
x_label (str, optional): The x-axis label. Defaults to None.
|
|
280
|
+
y_label (str, optional): The y-axis label. Defaults to None.
|
|
281
|
+
source_text (str, optional): The source text to add to the plot. Defaults to None.
|
|
282
|
+
kwargs (dict[str, any]): Additional keyword arguments to pass to the plot
|
|
283
|
+
|
|
284
|
+
Returns:
|
|
285
|
+
SubplotBase: The Matplotlib axes of the plot
|
|
286
|
+
"""
|
|
287
|
+
density = False
|
|
288
|
+
if cumulative:
|
|
289
|
+
density = True
|
|
290
|
+
|
|
291
|
+
ax = self.purchase_dist_s.hist(
|
|
292
|
+
bins=bins,
|
|
293
|
+
cumulative=cumulative,
|
|
294
|
+
ax=ax,
|
|
295
|
+
density=density,
|
|
296
|
+
color=COLORS["green"][500],
|
|
297
|
+
**kwargs,
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
ax.xaxis.set_major_formatter(lambda x, pos: human_format(x, pos, decimals=0))
|
|
301
|
+
|
|
302
|
+
ax = standard_graph_styles(ax)
|
|
303
|
+
|
|
304
|
+
if cumulative:
|
|
305
|
+
default_title = "Average Days Between Purchases cumulative Distribution"
|
|
306
|
+
default_y_label = "Percentage of Customers"
|
|
307
|
+
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
|
|
308
|
+
|
|
309
|
+
else:
|
|
310
|
+
default_title = "Average Days Between Purchases Distribution"
|
|
311
|
+
default_y_label = "Number of Customers"
|
|
312
|
+
ax.yaxis.set_major_formatter(lambda x, pos: human_format(x, pos, decimals=0))
|
|
313
|
+
|
|
314
|
+
ax = gu.standard_graph_styles(
|
|
315
|
+
ax,
|
|
316
|
+
title=gu.not_none(title, default_title),
|
|
317
|
+
y_label=gu.not_none(y_label, default_y_label),
|
|
318
|
+
x_label=gu.not_none(x_label, "Average Number of Days Between Purchases"),
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
if percentile_line is not None:
|
|
322
|
+
if percentile_line > 1 or percentile_line < 0:
|
|
323
|
+
raise ValueError("Percentile line must be between 0 and 1")
|
|
324
|
+
ax.axvline(
|
|
325
|
+
x=self.purchases_percentile(percentile_line),
|
|
326
|
+
color=COLORS["red"][500],
|
|
327
|
+
linestyle="--",
|
|
328
|
+
lw=2,
|
|
329
|
+
label=f"{percentile_line:.1%} of customers",
|
|
330
|
+
ymax=0.96,
|
|
331
|
+
)
|
|
332
|
+
ax.legend(frameon=False)
|
|
333
|
+
|
|
334
|
+
if source_text:
|
|
335
|
+
gu.add_source_text(ax=ax, source_text=source_text)
|
|
336
|
+
|
|
337
|
+
gu.standard_tick_styles(ax)
|
|
338
|
+
|
|
339
|
+
return ax
|
|
340
|
+
|
|
341
|
+
def purchases_percentile(self, percentile: float = 0.5) -> float:
|
|
342
|
+
"""Get the average number of days between purchases at a given percentile.
|
|
343
|
+
|
|
344
|
+
Args:
|
|
345
|
+
percentile (float): The percentile to get the average number of days between purchases at.
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
float: The average number of days between purchases at the given percentile.
|
|
349
|
+
"""
|
|
350
|
+
return self.purchase_dist_s.quantile(percentile)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class TransactionChurn:
|
|
354
|
+
"""A class to plot the churn rate by number of purchases.
|
|
355
|
+
|
|
356
|
+
Attributes:
|
|
357
|
+
purchase_dist_df (pd.DataFrame): The churn rate by number of purchases.
|
|
358
|
+
n_unique_customers (int): The number of unique customers in the dataframe.
|
|
359
|
+
"""
|
|
360
|
+
|
|
361
|
+
def __init__(self, df: pd.DataFrame, churn_period: float) -> None:
|
|
362
|
+
"""Initialize the TransactionChurn class.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
df (pd.DataFrame): A dataframe with the transaction data. The dataframe must have the columns customer_id
|
|
366
|
+
and transaction_date.
|
|
367
|
+
churn_period (float): The number of days to consider a customer churned.
|
|
368
|
+
|
|
369
|
+
Raises:
|
|
370
|
+
ValueError: If the dataframe does doesn't contain the columns customer_id and transaction_id.
|
|
371
|
+
"""
|
|
372
|
+
cols = ColumnHelper()
|
|
373
|
+
required_cols = [cols.customer_id, cols.transaction_date]
|
|
374
|
+
missing_cols = set(required_cols) - set(df.columns)
|
|
375
|
+
if len(missing_cols) > 0:
|
|
376
|
+
msg = f"The following columns are required but missing: {missing_cols}"
|
|
377
|
+
raise ValueError(msg)
|
|
378
|
+
|
|
379
|
+
purchase_dist_df = df[[cols.customer_id, cols.transaction_date]].copy()
|
|
380
|
+
# Truncate the transaction_date to the day
|
|
381
|
+
purchase_dist_df[cols.transaction_date] = df[cols.transaction_date].dt.floor("D")
|
|
382
|
+
purchase_dist_df = purchase_dist_df.drop_duplicates()
|
|
383
|
+
purchase_dist_df = purchase_dist_df.sort_values([cols.customer_id, cols.transaction_date])
|
|
384
|
+
purchase_dist_df["transaction_number"] = purchase_dist_df.groupby(cols.customer_id).cumcount() + 1
|
|
385
|
+
|
|
386
|
+
purchase_dist_df["last_transaction"] = (
|
|
387
|
+
purchase_dist_df.groupby(cols.customer_id)[cols.transaction_date].shift(-1).isna()
|
|
388
|
+
)
|
|
389
|
+
purchase_dist_df["transaction_before_churn_window"] = purchase_dist_df[cols.transaction_date] < (
|
|
390
|
+
purchase_dist_df[cols.transaction_date].max() - pd.Timedelta(days=churn_period)
|
|
391
|
+
)
|
|
392
|
+
purchase_dist_df["churned"] = (
|
|
393
|
+
purchase_dist_df["last_transaction"] & purchase_dist_df["transaction_before_churn_window"]
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
purchase_dist_df = (
|
|
397
|
+
purchase_dist_df[purchase_dist_df["transaction_before_churn_window"]]
|
|
398
|
+
.groupby(["transaction_number"])["churned"]
|
|
399
|
+
.value_counts()
|
|
400
|
+
.unstack()
|
|
401
|
+
)
|
|
402
|
+
purchase_dist_df.columns = ["retained", "churned"]
|
|
403
|
+
purchase_dist_df["churned_pct"] = purchase_dist_df["churned"].div(purchase_dist_df.sum(axis=1))
|
|
404
|
+
self.purchase_dist_df = purchase_dist_df
|
|
405
|
+
|
|
406
|
+
self.n_unique_customers = df[cols.customer_id].nunique()
|
|
407
|
+
|
|
408
|
+
def plot(
|
|
409
|
+
self,
|
|
410
|
+
cumulative: bool = False,
|
|
411
|
+
ax: Axes | None = None,
|
|
412
|
+
title: str | None = None,
|
|
413
|
+
x_label: str | None = None,
|
|
414
|
+
y_label: str | None = None,
|
|
415
|
+
source_text: str | None = None,
|
|
416
|
+
**kwargs: dict[str, any],
|
|
417
|
+
) -> SubplotBase:
|
|
418
|
+
"""Plot the churn rate by number of purchases.
|
|
419
|
+
|
|
420
|
+
Args:
|
|
421
|
+
cumulative (bool, optional): Whether to plot the cumulative distribution. Defaults to False.
|
|
422
|
+
ax (Axes, optional): The Matplotlib axes to plot the graph on. Defaults to None.
|
|
423
|
+
title (str, optional): The title of the plot. Defaults to None.
|
|
424
|
+
x_label (str, optional): The x-axis label. Defaults to None.
|
|
425
|
+
y_label (str, optional): The y-axis label. Defaults to None.
|
|
426
|
+
source_text (str, optional): The source text to add to the plot. Defaults to None.
|
|
427
|
+
kwargs (dict[str, any]): Additional keyword arguments to pass to the plot function.
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
SubplotBase: The Matplotlib axes of the plot
|
|
431
|
+
"""
|
|
432
|
+
if cumulative:
|
|
433
|
+
cumulative_churn_rate_s = self.purchase_dist_df["churned"].cumsum().div(self.n_unique_customers)
|
|
434
|
+
ax = cumulative_churn_rate_s.plot.area(
|
|
435
|
+
color=COLORS["green"][500],
|
|
436
|
+
**kwargs,
|
|
437
|
+
)
|
|
438
|
+
ax.set_xlim(self.purchase_dist_df.index.min(), self.purchase_dist_df.index.max())
|
|
439
|
+
else:
|
|
440
|
+
ax = self.purchase_dist_df["churned_pct"].plot.bar(
|
|
441
|
+
rot=0,
|
|
442
|
+
color=COLORS["green"][500],
|
|
443
|
+
width=0.8,
|
|
444
|
+
**kwargs,
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
standard_graph_styles(
|
|
448
|
+
ax,
|
|
449
|
+
title=gu.not_none(title, "Churn Rate by Number of Purchases"),
|
|
450
|
+
x_label=gu.not_none(x_label, "Number of Purchases"),
|
|
451
|
+
y_label=gu.not_none(y_label, "% Churned"),
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1.0))
|
|
455
|
+
|
|
456
|
+
if source_text:
|
|
457
|
+
gu.add_source_text(ax=ax, source_text=source_text)
|
|
458
|
+
|
|
459
|
+
return ax
|