-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuyer-behavior-summary-panel-data.qmd
4465 lines (3706 loc) · 190 KB
/
buyer-behavior-summary-panel-data.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Analysing Buyer Behaviour Using Consumer Panel Data
author: Abdullah Mahmood
date: last-modified
format:
html:
theme: cosmo
css: quarto-style/style.css
highlight-style: atom-one
mainfont: Palatino
fontcolor: black
monobackgroundcolor: white
monofont: Menlo, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace
fontsize: 13pt
linestretch: 1.4
number-sections: true
number-depth: 5
toc: true
toc-location: right
toc-depth: 5
code-fold: true
code-copy: true
cap-location: bottom
format-links: false
embed-resources: true
anchor-sections: true
code-links:
- text: GitHub Repo
icon: github
href: https://github.com/abdullahau/customer-analytics/
- text: Quarto Markdown
icon: file-code
href: https://github.com/abdullahau/customer-analytics/blob/main/buyer-behavior-summary-panel-data.qmd
html-math-method:
method: mathjax
url: https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
---
## Introduction
This is a python implementation of Bruce G.S. Hardie's [An Excel-based Introduction to Analysing Buyer Behaviour Using Consumer Panel Data](https://www.brucehardie.com/notes/042/) using [Polars](https://pola.rs).
Several leading market research firms (e.g., Kantar, IRI, Nielsen) collect so called consumer panel data and sell reports and analyses based on these data to interested parties. A large number of households are recruited to join the panel and they record all their grocery/HBA purchases. The idea of a panel is that we have repeated observations of the same people. The ability to track what individual households are purchasing over time can give important insights into what behavioural changes lie beneath observed changes in aggregate sales data. (terms panellist and household are used interchangeably) Nowadays, it is common for panellists to record their purchasing by scanning product barcodes via an app on their smartphones.
The objective of this notebook is to provide an introduction to basic analyses we can undertake using panel data. After briefing **describing the data** we will be working with, we present some preliminary **aggregate-level analyses**. Next we introduce some basic **brand performance measures** and consider the simple analyses that describe the **variation we observe in buyer behaviour** in a given time period. This analysis focuses on one brand at a time; next we consider some basic analyses that describe consumers’ **buying of multiple brands in a category**. We finish with some basic analyses that describe **how buyer behaviour evolves over time**, both for established products and new products.
Note: Whereas consumer panel data gives us information on the purchasing of a sample of customers for the whole category, the data in a firm’s transaction database gives us complete information on the purchasing of our products (but not those of our competitors). At a fundamental level, the types of reports developed by market research firms over the past 60+ years are a good starting point for the types of reports a firm should create as it seeks to understand the buying behaviour of its customers.
A traditional consumer panel works in the following manner:
1. When an individual first joins the panel, they complete a detailed questionnaire. A section of this questionnaire focuses on the demographics of their household. (This is typically updated once a year.)
2. After each shopping trip, each panellist records their purchases, scanning the barcode associated with each product and recording other information such as where the purchase was made (store or channel), the price paid, and the use of promotional deals. Twenty years ago, this would have been done using a custom handheld barcode scanner provided by the market research firm. These days, it is more common to use a smartphone app.
3. These data are uploaded to the research firm’s servers and merged with the purchases records of the other panellists. Each barcode is matched with detailed product information (e.g., category, brand, size, flavour) and this information is also stored in the database. The analyst can then create (typically product-category-specific) datasets for further analysis that tell us what each panellist purchased, when and where, and associated transaction- and/or product-specific data that may be of interest.
4. Panellists drop out of the panel all the time, and the research firm will be recruiting replacement households on a regular basis. When creating a dataset for further analysis, it is generally desirable to work with a so-called static sample of panellists, which comprises all those panellists active using the time period of interest; new panellists, as well as those that dropped out during the given time period, are excluded.
## Imports
### Import Packages
```{python}
import polars as pl
import altair as alt
import numpy as np
from great_tables import GT, style, loc, md
import gc
alt.renderers.enable("html")
```
### Import Panel Data
We will make use of two datasets as we explore the basic types of summaries of buyer behaviour that can be created using consumer panel data. The first contains data on the purchasing of established brands in a mature product category, while the second contains data on the purchasing of a new product. Both datasets were created using static samples. While these are small datasets and contain a subset of the information available in the research firm’s databases, they are more than sufficient to convey the logic of creating the key summaries of buyer behaviour. Neither dataset includes data on the demographics of each panellist. As such, we will not consider how to create reports that explore how behaviours differ across demographic groups (e.g., by age or geography). However, anyone comfortable with the analyses undertaken in this note should be able to work out how to create such reports for themselves.
#### Dataset 1
The file `edible_grocery.csv` contains two years of data from a panel of 5021 households on their purchasing in an unnamed edible grocery product category. (We intentionally do not identity the category and the associated brand names.) There are 119 SKUs in this category. 91 SKUs are associated with the four largest brands in the category, which we have named Alpha, Bravo, Charlie, and Delta. The remaining SKUs belong to very low-share brands and we grouped them under the brand Other.
*Note*: SKU - A stock-keeping unit (SKU) is a unique combination of the attributes (e.g., brand, package type, package size, flavour) that define the products in the category.
Each record in this file consists of seven fields:
- `panel_id` A unique identifier for each household.
- `trans_id` A unique identifier for the purchase occasion.
- `week` The week number in which the purchase occurred. Week 1 corresponds to the calendar week starting on January 1, 20xy. Week 53 corresponds to the calendar week starting on December 31, 20xy.
- `sku_id` The SKU code.
- `units` The number of units purchased on the particular purchase occasion.
- `price` The price per unit paid at the point of purchase.
- `brand` The brand associated with the SKU purchased.
The associated file `sku_weight.csv` gives us the weight (in grams) of each SKU. There are two fields: `sku_id` and `weight`.
```{python}
grocery_lf = pl.scan_csv(
source="data/panel-datasets/edible_grocery.csv",
has_header=True,
separator=",",
schema={
'panel_id': pl.UInt32,
'trans_id': pl.Int32,
'week': pl.UInt16,
'sku_id': pl.UInt8,
'units': pl.Int16,
'price': pl.Float32,
'brand': pl.Categorical})
grocery_lf.head().collect()
```
```{python}
sku_lf = pl.scan_csv(
source="data/panel-datasets/sku_weight.csv",
has_header=True,
separator=",",
schema={
'sku_id': pl.UInt8,
'weight': pl.Int16})
sku_lf.head().collect()
```
```{python}
#| code-fold: false
panel_size = 5021
```
#### Dataset 2
“Kiwi Bubbles” is a masked name for a shelf-stable juice drink, aimed primarily at children, which is sold as a multipack with several single-serve containers bundled together. Prior to national launch, it underwent a year-long test conducted in two of IRI’s BehaviorScan markets. The file `kiwibubbles_trans.csv` contains purchasing data for the new product, drawn from 1300 panellists in Market 1 and 1499 panellists in Market 2. (The purchasing of other brands in the category has been excluded from the dataset.)
Each record in this file consists of five fields:
- `ID` A unique identifier for each household.
- `Market` 1 or 2.
- `Week` The week in which the purchase occurred.
- `Day` The day of the week in which the purchase occurred. (The product was launched on day 1 of week 1.)
- `Units` The number of units of the new product purchased on the particular purchase occasion.
```{python}
kiwi_lf = pl.scan_csv(
source="data/panel-datasets/kiwibubbles_trans.csv",
has_header=True,
separator=",",
schema={
'ID': pl.UInt16,
'Market': pl.UInt8,
'Week': pl.Int16,
'Day': pl.Int16,
'Units': pl.Int16})
kiwi_lf.head().collect()
```
### Reusable Functions
```{python}
# Weekly Grocery Sales LazyFrame (Query Plan): Weekly 'spend' by 'Category', 'Brand' or 'All'
def weekly_spend_summary(brand, lf):
summary = (
lf
.select(['week', 'units', 'price', 'brand'])
.with_columns(((pl.col('units') * pl.col('price'))).alias('spend'))
)
if brand == 'Category': # Return LazyFrame of total category
summary = summary.group_by('week')
elif brand == 'All': # Return LazyFrame of all brands
summary = summary.group_by('week', 'brand')
else: # Return LazyFrame of specified brand
summary = summary.filter(
pl.col('brand') == brand
).group_by('week', 'brand')
summary = summary.agg(
pl.col("spend").sum().alias('Weekly Spend')
).sort('week')
return summary
```
```{python}
# Weekly Grocery Volume Sales LazyFrame (Query Plan): Weekly 'volume' by 'Brand' or 'All'
def weekly_vol_summary(brand, lf):
with pl.StringCache():
lf = (
lf
.join(
other=sku_lf,
left_on="sku_id",
right_on="sku_id"
)
.select(['week', 'units', 'brand', 'weight'])
)
if brand != 'All':
brand = [brand] if type(brand) == str else brand
lf = lf.filter(
pl.col('brand').is_in(*[brand])
)
summary = lf.with_columns(
(((pl.col('units') * pl.col('weight'))/1000)).alias('volume')
).group_by('week', 'brand').agg(
pl.col("volume").sum().alias('Weekly Volume')
).sort('week')
return summary
```
```{python}
# Altair Weekly Line Plot
def weekly_plot(dataframe, y, year=2, color=None, title="", y_axis_label="", pct=False, legend=False):
# Configure the color encoding only if color is provided
if color is not None:
color_encoding = alt.Color(
f'{color}:N', # N = a discrete unordered category
legend=alt.Legend(title=color) if legend else None # Add legend conditionally
)
else:
color_encoding = alt.Color() # No color encoding
chart = alt.Chart(dataframe).mark_line(strokeWidth=1).encode(
x = alt.X(
'week',
axis=alt.Axis(
values=np.arange(0, (year*52) + 1, 13), # Explicitly specify quarter-end weeks
labelExpr="datum.value", # Show only these labels
title='Week'
)
),
y = alt.Y(
f'{y}:Q', # Q = a continuous real-valued quantity
title=y_axis_label,
axis=alt.Axis(format="$,.0f") if not pct else alt.Axis(format=",.0%")
),
color = color_encoding
).properties(
width=650,
height=250,
title=title
).configure_view(
stroke=None
).configure_axisY(
# grid=False # turn off y-axis grid if required
)
return chart # alt.JupyterChart(chart)
```
```{python}
# Annual Sales Summary LazyFrame for All Brands
def annual_sales_summary():
summary = (
weekly_spend_summary('All', grocery_lf)
.with_columns((pl.col("week") / 52).ceil().alias('year'))
.group_by(['year', 'brand'])
.agg(pl.col("Weekly Spend").sum().alias('Yearly Sales'))
).sort('year')
return summary
```
```{python}
def freq_dist_plot(
data,
column,
bin_edges,
labels,
x_title,
y_title,
chart_title,
subtitle,
width=650,
height=250,
label_angle=0,
left_closed=True,
compute_rel_freq=True
):
"""
Creates a standardized Altair bar chart for relative frequency distribution plots.
Parameters:
- data (Polars LazyFrame or DataFrame): Input dataset.
- column (str): Column to analyze for distribution.
- bin_edges (array-like): Edges for binning.
- labels (list of str): Labels for the bins.
- x_title (str): Title for the x-axis.
- y_title (str): Title for the y-axis.
- chart_title (str): Main title for the chart.
- subtitle (str): Subtitle for the chart.
- width (int, optional): Width of the chart. Default is 650.
- height (int, optional): Height of the chart. Default is 250.
- label_angle (int, optional): Angle for x-axis labels. Default is 0.
- left_closed (bool, optional): Whether bins are left-closed. Default is True.
- compute_rel_freq (bool, optional): Whether to compute relative frequencies. Default is True.
Returns:
- alt.Chart: The generated Altair chart.
"""
# Apply binning to the data
binned_data = data.with_columns(
pl.col(column).cut(bin_edges, labels=labels, left_closed=left_closed).alias("cut")
)
# Optionally compute relative frequencies
if compute_rel_freq:
binned_data = (
binned_data
.group_by("cut")
.agg(pl.col("cut").count().alias("Frequency"))
.with_columns(
(pl.col("Frequency") / pl.col("Frequency").sum()).alias("% of Total")
)
.collect()
)
# Create the Altair chart
chart = alt.Chart(binned_data).mark_bar().encode(
x=alt.X("cut:O", axis=alt.Axis(labelAngle=label_angle, title=x_title), sort=labels),
y=alt.Y("% of Total:Q", axis=alt.Axis(format=".0%", title=y_title)),
).properties(
width=width,
height=height,
title={"text": chart_title, "subtitle": subtitle},
)
return chart
```
## Preliminaries
Before we start analysing household-level behaviour, let us first get a sense of the general sales patterns observed in this category.
Our initial objective is to plot weekly revenue for all the brands and the overall category, respectively, and then plot weekly (volume) market shares for target brands.
### Weekly Sales Pattern
```{python}
# Weekly Sales Pivot Table - Polars DataFrame
# For visualizing and inspecting only
weekly_spend_summary('All', grocery_lf).collect().pivot(
on="brand",
index="week",
values="Weekly Spend",
sort_columns=True,
).with_columns(
pl.sum_horizontal(pl.exclude('week')).alias("Total") # Row total
).sort("week")
```
```{python}
weekly_plot(dataframe=weekly_spend_summary('Category', grocery_lf).collect(),
y='Weekly Spend',
title='Category - Weekly Revenue',
y_axis_label='Spend ($)',
pct=False,
legend=False)
```
```{python}
weekly_plot(dataframe=weekly_spend_summary('Alpha', grocery_lf).collect(),
y='Weekly Spend',
title='Alpha - Weekly Revenue',
y_axis_label='Spend ($)',
pct=False,
legend=False)
```
```{python}
weekly_plot(dataframe=weekly_spend_summary('Bravo', grocery_lf).collect(),
y='Weekly Spend',
title='Bravo - Weekly Revenue',
y_axis_label='Spend ($)',
pct=False,
legend=False)
```
### Weekly (Volume) Market Share
```{python}
# Weekly (volume) market share
pct_volume =(
weekly_vol_summary('All', grocery_lf)
.collect()
.pivot(
on='brand',
index='week',
values='Weekly Volume',
sort_columns=True
)
.with_columns(
(pl.col("*").exclude("week")) / pl.sum_horizontal(pl.exclude('week'))
)
)
pct_volume
```
```{python}
with pl.StringCache():
pct_volume_plot = (
weekly_vol_summary('All', grocery_lf)
.group_by('week')
.agg(
pl.col('Weekly Volume').sum().alias('Total Weekly Volume')
)
.join(
other=weekly_vol_summary(['Alpha', 'Bravo'], grocery_lf),
on='week',
)
.filter(
(pl.col('brand').is_in(['Alpha', 'Bravo']))
)
.with_columns(
# compute brand wise % of total volume sale
(pl.col('Weekly Volume') / pl.col('Total Weekly Volume')).alias('pct_volume')
)
).collect()
weekly_plot(dataframe=pct_volume_plot,
y='pct_volume',
color='brand',
title="Volume Market Share - Alpha vs. Bravo",
y_axis_label="% of Weekly Total",
pct=True,
legend=True)
```
There appears to be a **high level of competition** between these two brands. What is the correlation in their market shares?
We observe that there is a strong negative correlation between the shares of Alpha and Bravo: an increase in one brand’s share is associated with a corresponding decrease in the share of the other brand.
```{python}
corr_matrix = (
pct_volume.select(
pl.col('*').exclude('week') # Exclude 'week' column
)
.corr() # Compute the correlation matrix
.with_columns(
pl.Series(pct_volume.columns[1:]).alias("index")
)
)
columns = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Other']
(
GT(corr_matrix, rowname_col='index')
.tab_header(title="Correlation Matrix of Weekly (Volume) Market Share")
.fmt_number(columns=columns)
.data_color(
columns=columns,
domain=[-1, 1],
palette=["rebeccapurple", "white", 'orange']
)
.tab_style(
style=[
style.text(color="black"),
style.fill('white'),
],
locations=[
loc.body(0,0),
loc.body(1,1),
loc.body(2,2),
loc.body(3,3),
loc.body(4,4)
]
)
)
```
### Annual Sales
Let us finish this preliminary analysis of the data by computing the annual sales of each brand.
```{python}
annual_sales_pivot = annual_sales_summary().collect().pivot(
on='brand',
index='year',
sort_columns=True
).with_columns(
pl.sum_horizontal(pl.all().exclude('year')).alias("Total") # add totals column
)
(
GT(annual_sales_pivot, rowname_col="year")
.tab_header(title="Annual Sales ($)")
.tab_stubhead(label="Year")
.fmt_currency()
.fmt_integer(columns='year')
.data_color(
columns=columns,
domain=[100, 36_000],
palette=["white", "rebeccapurple"]
)
)
```
```{python}
annual_change_sales = annual_sales_pivot.with_columns(
pl.col('*').exclude('year').pct_change()
).filter(
pl.col('year') == 2
).unpivot(
index="year", # Keep 'year' as a fixed identifier
value_name='% Change',
variable_name='brand'
)
(
GT(annual_change_sales, rowname_col='brand')
.tab_header(title='% Change in Annual Sales')
.tab_stubhead(label="Brands")
.fmt_percent()
.data_color(
columns=['% Change'],
domain=[-0.3, 0.3],
palette=['orange', 'white', 'rebeccapurple']
)
.cols_hide('year')
.cols_label(brand='Y-o-Y % Change')
)
```
```{python}
chart = alt.Chart(annual_sales_summary().collect()).mark_bar().encode(
x=alt.X("brand:N",
axis=alt.Axis(title='Brands', labelAngle=0)),
xOffset="year:N",
y=alt.Y("Yearly Sales:Q",
axis=alt.Axis(format="$,.0f"),
title='Yearly Revenue ($)'),
color=alt.Color("year:N", title='Year'),
).properties(
width=650,
height=250,
title='Year 1 & Year 2 Revenues'
).show()
```
```{python}
base = alt.Chart(annual_change_sales).encode(
x=alt.X("brand:N",
title='Brand',
axis=alt.Axis(labelAngle=0)
),
y=alt.Y("% Change:Q",
axis=alt.Axis(format=".0%")
),
color=alt.condition(
alt.datum["% Change"] > 0, # fixed this
alt.value("green"), # The positive color
alt.value("red") # The negative color
),
text=alt.Text(
'% Change',
format=(".1%")
)
).properties(
width=650,
height=250,
title='Y-o-Y % Change in Revenue'
)
chart = base.mark_bar() + base.mark_text(
align='center',
baseline=alt.expr(alt.expr.if_(alt.datum['% Change'] >= 0, 'bottom', 'top')),
dy=alt.expr(alt.expr.if_(alt.datum['% Change'] >= 0, -2, 2)),
dx=0)
chart.show()
```
### Annual Market Share
```{python}
market_share = annual_sales_pivot.with_columns(
pl.col('*').exclude('year') / pl.col('Total')
)
(
GT(market_share, rowname_col="year")
.tab_header(title="Annual Market Share (%)")
.tab_stubhead(label="Year")
.fmt_percent()
.cols_hide('Total')
.data_color(
columns=columns,
domain=[0, 0.5],
palette=["white", "rebeccapurple"]
)
)
```
```{python}
annual_change_share = market_share.drop('Total').with_columns(
pl.col('*').exclude('year').pct_change()
).filter(
pl.col('year') == 2
).unpivot(
index="year", # Keep 'year' as a fixed identifier
value_name='% Change',
variable_name='brand'
)
(
GT(annual_change_share, rowname_col='brand')
.tab_header(title='% Change in Market Share')
.tab_stubhead(label="Brands")
.fmt_percent()
.data_color(
columns=['% Change'],
domain=[-0.3, 0.3],
palette=['orange', 'white', 'rebeccapurple']
)
.cols_hide('year')
.cols_label(brand='Y-o-Y % Change')
)
```
```{python}
base = alt.Chart(annual_change_share).encode(
x=alt.X("brand:N",
title='Brands',
axis=alt.Axis(labelAngle=0)
),
y=alt.Y("% Change:Q",
axis=alt.Axis(format=".0%")
),
color=alt.condition(
alt.datum["% Change"] > 0, # fixed this
alt.value("green"), # The positive color
alt.value("red") # The negative color
),
text=alt.Text(
'% Change',
format=(".1%")
)
).properties(
width=650,
height=250,
title='% Change in Annual Market Share'
)
chart = base.mark_bar() + base.mark_text(
align='center',
baseline=alt.expr(alt.expr.if_(alt.datum['% Change'] >= 0, 'bottom', 'top')),
dy=alt.expr(alt.expr.if_(alt.datum['% Change'] >= 0, -3, 3)),
dx=0)
chart.show()
```
### Average SKU Price
```{python}
avg_sku_price = grocery_lf.select(
['week', 'sku_id', 'price', 'brand']
).filter(
(pl.col('week') <= 52) & # pricing in the first year
(pl.col('brand') == 'Alpha') # Filter by Alpha brand
).group_by('brand', 'sku_id').agg(
pl.col('price').mean()
).drop('brand').sort(
pl.col('sku_id').cast(pl.Int8)
)
(
GT(avg_sku_price.collect(), rowname_col='sku_id')
.tab_header(title='Alpha - Average SKU Retail Prices')
.tab_stubhead(label="SKU IDs")
.fmt_currency()
.data_color(
columns=['price'],
domain=[1, 15],
palette=['white', 'rebeccapurple']
)
.cols_label(price='Average Price ($)')
)
```
```{python}
avg_sku_price.drop(pl.col('sku_id')).describe()
```
::: example-text
*Garbage Collect*
```{python}
exceptions = ['grocery_lf', 'sku_lf', 'kiwi_lf', 'In', 'exceptions', 'active_variables']
active_variables = [
var for var, value in globals().items()
if not var.startswith('_') # Exclude variables that start with "_"
and var not in exceptions # Exclude variables in the exceptions list
and isinstance(value, (pl.LazyFrame, pl.DataFrame, pl.Series, alt.Chart, alt.LayerChart, list, int, float, str, np.ndarray, np.int64, np.float32)) # Remove these types only
]
for var in active_variables:
del globals()[var]
del active_variables, exceptions, var
gc.collect()
```
:::
## Exploring Variation in Buyer Behaviour
### Introduction
The objective here is to explore how to perform the basic analyses that describe the variation we observe in buyer behaviour in a given time period. We will continue to work with the edible grocery dataset, exploring both purchase frequency and spend.
Before we can doing any analysis, we need to create some summary datasets. The first will summarise **how many times each panellist purchased each brand as well as in the category**. The second will summarise **how much each panellist spent on each brand and in the category**.
```{python}
grocery_lf.filter(
(pl.col('panel_id') == 3102016) &
(pl.col('trans_id') == 844)
).collect()
```
On this one shopping trip (`trans_id` = 844), panellist `3102021` purchased a total of six items: three packs of SKU 5, two packs of SKU 15, and one pack of SKU 89. They purchased two different brand, Alpha and Delta.
Why are three lines for SKU 5 and not one line with units = 3. This is simply a function of how the items were scanned at the checkout. Some checkout operators will scan the three items separately; this would result in three lines in the transaction file, each with units = 1. Others will scan the item and press “3” on their till, resulting in one line in the transaction file with units = 3.
By convention, this purchase occasion is recorded as one **category transaction**, one Alpha transaction, and one Delta transaction. The number of units of Alpha purchased is five. When we say that the panellist made one category transaction, we mean they purchased at least one item in the category on that shopping trip. When we say that the panellist made one Alpha transaction, we mean they purchased at least one item associated with the brand on that shopping trip.
In order to analyse buyer behaviour in terms of transactions, we need to know the **number of brand and category transactions for each person**. We cannot work directly with the dataset we have been using; we effectively need to collapse the five rows associated with Alpha into one. This will require some intermediate analysis, which we undertake in the following manner.
Result of the intermediate prep should produce a dataset that summarizes transaction 844 by panellist 3102016 as 1 occasion of Alpha brand purchase and 1 occasion of Delta brand purchase:
{fig-align="center" width="734"}
### Panellist-Level Data Preparation
{fig-align="center" width="605"}
**One row per transaction**, with a binary indicator of whether or not each brand was purchased.
- Filter for year == 1, group by transaction ID, panel ID and brand, then count unique panel_ids per transaction and brand
- Each panelist has done some number of transactions. Group unique transactions and obtain the count of transactions occasions in which any listed brand was purchased
- Note: this is not a sum of total units (by brand) purchased per panellist.
- Note: Because there are multiple entires for the same transaction ID, we are not doing a count of brand instance per panelist (without trans_id grouping) as this would duplicate the occasions in some cases.
- Produce a dataset where there is just one row per transaction, with a binary indicator of whether or not each brand was purchased.
- Create a new column to track category purchase. Each row is an instance of at least one brand purchase so category column is set to 1.
**Panellist-level *transaction* summary**
The function below executes a query plan which summarizes each panellist's purchase occasions (transactions) for each brand
```{python}
def trans_summary(brand, lf, year):
# Primary Step: Filter by Year 1 and Remove Unused Columns
filtered_lf = lf.filter(
(pl.col('week') <= (year * 52)) &
(pl.col('week') > ((year - 1) * 52))
).drop(
pl.col('week','sku_id')
)
# Intermediate Step: Group by trans_id, panel_id, and brand
group_trans = filtered_lf.drop(
pl.col('price', 'units')
).group_by(
'trans_id', 'panel_id', 'brand'
).n_unique()
if brand == "Category":
# Panellist-level category transaction summary
summary = group_trans.group_by(
'panel_id'
).n_unique()
else:
# Panellist-level brand transaction summary
summary = group_trans.filter(
pl.col('brand') == brand
).group_by(
'panel_id'
).n_unique()
return summary.select(
pl.col('panel_id'),
pl.col('trans_id').alias('# of Purchases'),
pl.col('brand').alias('Brands Purchased')
)
```
```{python}
def trans_pivot(lf, year):
# Primary Step: Filter by Year 1 and Remove Unused Columns
filtered_lf = lf.filter(
(pl.col('week') <= (year * 52)) &
(pl.col('week') > ((year - 1) * 52))
).drop(
pl.col('week','sku_id')
)
# Intermediate Step: Group by trans_id, panel_id, and brand
group_trans = filtered_lf.drop(
pl.col('price', 'units')
).group_by(
'trans_id', 'panel_id', 'brand'
).n_unique() # count of unique entires
summary = group_trans.collect().pivot(
on='brand',
index='panel_id',
values='panel_id',
aggregate_function="len"
).join(
other=group_trans.group_by('panel_id').n_unique().drop('brand').collect(),
on='panel_id'
).rename(
{'trans_id': 'Category'}
).drop(
pl.col('panel_id')
)
return summary
```
**Panellist-level *spend* summary**
The function below executes a query plan which summarizes the amount each panellist spent on each brand (and in the category) during year 1.
```{python}
def spend_summary(brand, lf, year):
group_spend = lf.filter(
(pl.col('week') <= (year * 52)) &
(pl.col('week') > ((year - 1) * 52))
).drop(
pl.col('week','sku_id')
).with_columns(
((pl.col('units') * pl.col('price'))).alias('spend')
)
if brand == "Category":
# Panellist-level category spend summary
summary = group_spend.drop(
pl.col('units', 'price', 'brand')
).group_by(
'panel_id'
).agg(
pl.col('spend').sum()
)
else:
# Panellist-level brand spend summary
summary = group_spend.drop(
pl.col('units', 'price')
).group_by(
'panel_id', 'brand'
).agg(
pl.col('spend').sum()
).filter(
pl.col('brand') == brand
).drop('brand')
return summary
```
```{python}
def spend_pivot(lf, year):
group_spend = lf.filter(
(pl.col('week') <= (year * 52)) &
(pl.col('week') > ((year - 1) * 52))
).drop(
pl.col('week','sku_id')
).with_columns(
((pl.col('units') * pl.col('price'))).alias('spend')
).collect().pivot(
on='brand',
index='panel_id',
values='spend',
aggregate_function='sum'
).select(
'Alpha', 'Bravo', 'Charlie', 'Delta', 'Other'
)
return group_spend
```
**Panellist-level *volume purchasing* summary**
The function below executes a query plan which summarises each panellist’s volume purchasing in year 1.
```{python}
def vol_summary(brand, lf, year):
with pl.StringCache():
group_vol = lf.filter(
(pl.col('week') <= (year * 52)) &
(pl.col('week') > ((year - 1) * 52))
).join(
other=sku_lf,
left_on='sku_id',
right_on='sku_id'
).drop(
pl.col('week','sku_id')
).with_columns(
# volume column that is the product of weight of each SKU and the units of SKU sold
(((pl.col('units') * pl.col('weight'))/1000)).alias('volume') # # weight from grams to kilograms
).drop(
pl.col('units', 'price', 'weight')
)
if brand == "Category":
# Panellist-level category volume sales summary
summary = group_vol.drop(
pl.col('brand')
).group_by(
'panel_id'
).agg(
pl.col('volume').sum()
)
else:
# Panellist-level brand volume sales summary
summary = group_vol.group_by(
'panel_id', 'brand'
).agg(
pl.col('volume').sum()
).filter(
pl.col('brand') == brand
).drop('brand')
return summary
```
```{python}
def vol_pivot(lf, year):
with pl.StringCache():
group_vol = lf.filter(
(pl.col('week') <= (year * 52)) &
(pl.col('week') > ((year - 1) * 52))
).join(
other=sku_lf,
left_on='sku_id',
right_on='sku_id'
).drop(
pl.col('week','sku_id')
).with_columns(
# volume column that is the product of weight of each SKU and the units of SKU sold
(((pl.col('units') * pl.col('weight'))/1000)).alias('volume') # # weight from grams to kilograms
).drop(
pl.col('units', 'price', 'weight')
).collect().pivot(
on='brand',
index='panel_id',
values='volume',
aggregate_function='sum'
).select(
'Alpha', 'Bravo', 'Charlie', 'Delta', 'Other'
)
return group_vol
```
Looking at panellist-level spend and panellist-level volume purchasing, we note that for each row, `Category` equals the sum of the brand numbers, as we would expect. But this is not always the case in panellist-level transactions. Why is the sum of the brand-specific numbers sometimes greater than the associated category number?
Answer: Because a single transactions (once grouped) can have occasions of multiple brand purchases but the transaction only counts as one occasion of a category purchase. Consider the panellist `3102016` and her transaction ID `844`, The 4 entires on the one transaction ID count as a single category transaction, a single Alpha brand transaction and a single Delta transaction. The category transaction count is not a sum of brand purchase transaction count because regardless of the brand(s) and quantities purchased, the panelist purchased the category once in that transaction only.
### Examining Purchase Frequency
Two standard brand performance metrics that summarize purchasing behaviour are **penetration** and **purchases per buyer (PPB)**.
- *Penetration* is the percentage of households buying the product/category at least once in the given time period.
- In order to compute this, we need to know the number of panellists buying the product at least once in the time period of interest and the size of the panel during this period.
- *Purchases per buyer (PPB)* is the average number of times (separate shopping trips) the product/category was purchased (in the given time period) by those households that made at least one product/category purchase (in the given time period).
- i.e. purchases per buyer (PPB) is the average number of times the product was purchased (in the given time period) per buyer.
- This is computed as the total number of purchase occasions on which the product was purchased by the panellists (in the time period of interest) divided by the number of panellists that purchased the product at least once (in the time period of interest).
Looking at *panellist-level transaction summary*, we see that there are 4574 rows in this table, meaning that we have summary data on the purchasing of 4574 households in year 1. But there are 5021 households in the panel. What has happened to the remaining 447 households? They did not make any category purchase during the year. (But they will have purchased in other categories.)
```{python}
# the number of panellists who purchased each brand at least once in year 1
buyers = trans_pivot(grocery_lf, 1).count().select(
'Alpha', 'Bravo', 'Charlie', 'Delta', 'Other', 'Category'
).unpivot(
variable_name='brand',
value_name='buyers'
)