SegTransactionStats Segmentation
Segment Performance Analysis for Retail Business Intelligence.
Business Context
Retailers need to understand performance differences across various business dimensions - whether comparing customer segments, store locations, product categories, brands, channels, or any other grouping. This module transforms transactional data into actionable insights by calculating key performance metrics for any segment or combination of segments.
The Business Problem
Business stakeholders receive segment data but struggle to answer performance questions: - Which stores/categories/customer segments generate the most revenue? - How do transaction patterns differ between segments? - What's the customer density and spending behavior by segment? - Are certain combinations of segments more valuable than others?
Without segment performance analysis, decisions are made on incomplete information rather than data-driven insights about segment value and behavior.
Real-World Applications
Customer Segment Analysis
- Compare RFM segments: Which customer types drive the most revenue?
- Analyze geographic segments: Regional performance differences
- Age/demographic segments: Spending patterns by customer characteristics
Store/Location Analysis
- Store performance comparison: Revenue per customer, transaction frequency
- Regional analysis: Market penetration and customer behavior by area
- Channel analysis: Online vs in-store performance metrics
Product/Category Analysis
- Category performance: Which product lines drive customer frequency?
- Brand analysis: Private label vs national brand customer behavior
- SKU analysis: Performance metrics for product rationalization decisions
Multi-Dimensional Analysis
- Store + Customer segment: High-value customers by location
- Category + Channel: Product performance across sales channels
- Brand + Geography: Regional brand performance variations
This module calculates comprehensive statistics including spend, customer counts, transaction frequency, average basket size, and custom business metrics for any segment combination.
SegTransactionStats
Calculates transaction performance statistics for any business segment or dimension.
Analyzes transaction data across segments like customer types, store locations, product categories, brands, channels, or any combination to reveal performance differences and guide business decisions.
The class automatically calculates key retail metrics including total spend, unique customers, transaction frequency, spend per customer, and custom aggregations for comparison across segments.
Source code in pyretailscience/segmentation/segstats.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 | |
df: pd.DataFrame
property
Returns the dataframe with the transaction statistics by segment.
__init__(data, segment_col='segment_name', calc_total=None, extra_aggs=None, calc_rollup=None, rollup_value='Total', unknown_customer_value=None, grouping_sets=None)
Calculates transaction statistics by segment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
DataFrame | Table
|
The transaction data. The dataframe must contain the columns customer_id, unit_spend and transaction_id. If the dataframe contains the column unit_quantity, then the columns unit_spend and unit_quantity are used to calculate the price_per_unit and units_per_transaction. |
required |
segment_col |
str | list[str]
|
The column or list of columns to use for the segmentation. Defaults to "segment_name". |
'segment_name'
|
calc_total |
bool | None
|
Whether to include the total row. Defaults to True if grouping_sets is None. Cannot be used with grouping_sets parameter. Note: This parameter is planned for deprecation. Use grouping_sets parameter for new code. |
None
|
extra_aggs |
dict[str, tuple[str, str]]
|
Additional aggregations to perform. The keys in the dictionary will be the column names for the aggregation results. The values are tuples with (column_name, aggregation_function), where: - column_name is the name of the column to aggregate - aggregation_function is a string name of an Ibis aggregation function (e.g., "nunique", "sum") Example: {"stores": ("store_id", "nunique")} would count unique store_ids. |
None
|
calc_rollup |
bool | None
|
Whether to calculate rollup totals. Defaults to False if grouping_sets is None. When True and multiple segment columns are provided, the method generates subtotal rows for both: - Prefix rollups: progressively aggregating left-to-right (e.g., [A, B, Total], [A, Total, Total]). - Suffix rollups: progressively aggregating right-to-left (e.g., [Total, B, C], [Total, Total, C]). A grand total row is also included when calc_total is True. Note: This differs from grouping_sets='rollup' which generates only prefix rollups (SQL standard). Performance: adds O(n) extra aggregation passes where n is the number of segment columns. For large hierarchies, consider disabling rollups or reducing columns. Cannot be used with grouping_sets parameter. Note: This parameter is planned for deprecation. Use grouping_sets parameter for new code. |
None
|
rollup_value |
Any | list[Any]
|
The value to use for rollup totals. Can be a single value applied to all columns or a list of values matching the length of segment_col, with each value cast to match the corresponding column type. Defaults to "Total". |
'Total'
|
unknown_customer_value |
int | str | Scalar | BooleanColumn | None
|
Value or expression identifying unknown customers for separate tracking. When provided, metrics are split into identified, unknown, and total variants. Accepts simple values (e.g., -1), ibis literals, or boolean expressions (e.g., data["customer_id"] < 0). Requires customer_id column. Defaults to None. |
None
|
grouping_sets |
Literal['rollup', 'cube'] | list[list[str] | tuple[str, ...]] | None
|
Grouping sets mode. Mutually exclusive with calc_total/calc_rollup when explicitly set. - "rollup": SQL ROLLUP (hierarchical aggregation from right to left). Generates [A,B,C], [A,B], [A], []. - "cube": SQL CUBE (all possible combinations). Generates 2^n grouping sets for n dimensions. - list: Custom grouping sets (list of lists/tuples). Specify arbitrary dimension combinations. Each element must be a list or tuple of column names from segment_col. Empty list/tuple () represents grand total. Automatically deduplicates and validates column names. - None: Use calc_total/calc_rollup behavior (default). Defaults to None. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If grouping_sets is used with explicit calc_total or calc_rollup. |
ValueError
|
If grouping_sets is not a valid value. |
Example
Hierarchical rollup using grouping_sets
stats = SegTransactionStats( ... data=df, ... segment_col=["region", "store", "product"], ... grouping_sets="rollup", ... )
All combinations using CUBE
stats = SegTransactionStats( ... data=df, ... segment_col=["region", "store", "product"], ... grouping_sets="cube", ... )
Custom grouping sets for specific dimension combinations
stats = SegTransactionStats( ... data=df, ... segment_col=["region", "store", "product"], ... grouping_sets=[ ... ("region", "product"), # Regional product performance (skip store) ... ("product",), # Product-only totals ... () # Grand total ... ], ... )
Legacy behavior (backward compatible)
stats = SegTransactionStats( ... data=df, ... segment_col=["region", "store"], ... calc_total=True, ... calc_rollup=False, ... )
Source code in pyretailscience/segmentation/segstats.py
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 | |
plot(value_col, title=None, x_label=None, y_label=None, ax=None, orientation='vertical', sort_order=None, source_text=None, hide_total=True, **kwargs)
Plots the value_col by segment.
.. deprecated::
This method is deprecated. Use :func:pyretailscience.plots.bar.py instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value_col |
str
|
The column to plot. |
required |
title |
str
|
The title of the plot. Defaults to None. |
None
|
x_label |
str
|
The x-axis label. Defaults to None. When None the x-axis label is blank when the
orientation is horizontal. When the orientation is vertical it is set to the |
None
|
y_label |
str
|
The y-axis label. Defaults to None. When None the y-axis label is set to the
|
None
|
ax |
Axes
|
The matplotlib axes object to plot on. Defaults to None. |
None
|
orientation |
Literal['vertical', 'horizontal']
|
The orientation of the plot. Defaults to "vertical". |
'vertical'
|
sort_order |
Literal['ascending', 'descending', None]
|
The sort order of the segments. Defaults to None. If None, the segments are plotted in the order they appear in the dataframe. |
None
|
source_text |
str
|
The source text to add to the plot. Defaults to None. |
None
|
hide_total |
bool
|
Whether to hide the total row. Defaults to True. |
True
|
**kwargs |
dict[str, Any]
|
Additional keyword arguments to pass to the Pandas plot function. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
SubplotBase |
SubplotBase
|
The matplotlib axes object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sort_order is not "ascending", "descending" or None. |
ValueError
|
If the orientation is not "vertical" or "horizontal". |
ValueError
|
If multiple segment columns are used, as plotting is only supported for a single segment column. |
Source code in pyretailscience/segmentation/segstats.py
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 | |
cube(*columns)
Generate CUBE grouping sets (all possible combinations).
CUBE generates all 2^n combinations of the specified columns, from full detail down to grand total. Returns a list of tuples that can be passed directly to grouping_sets, or used with fixed columns in a nested list specification.
This matches SQL's GROUP BY CUBE(A, B), C syntax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*columns |
str
|
Column names to include in the CUBE operation |
()
|
Returns:
| Type | Description |
|---|---|
list[tuple[str, ...]]
|
list[tuple[str, ...]]: List of tuples representing all CUBE combinations |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no columns are provided |
TypeError
|
If any column is not a string |
UserWarning
|
If more than MAX_CUBE_DIMENSIONS_WITHOUT_WARNING columns |
Example
from pyretailscience.segmentation import cube
Simple CUBE - returns list of tuples
cube("store", "region") [("store", "region"), ("store",), ("region",), ()]
Use directly (equivalent to explicit list of tuples)
stats = SegTransactionStats( ... data=df, ... segment_col=["store", "region", "date"], ... grouping_sets=cube("store", "region", "date") ... )
CUBE with fixed columns - wrap in tuple
stats = SegTransactionStats( ... data=df, ... segment_col=["store", "region", "date"], ... grouping_sets=[(cube("store", "region"), "date")] ... )
Produces 4 grouping sets (2^2 from CUBE):
[("store", "region", "date"), ("store", "date"), ("region", "date"), ("date",)]
Source code in pyretailscience/segmentation/segstats.py
rollup(*columns)
Generate ROLLUP grouping sets (hierarchical aggregation levels).
ROLLUP generates n+1 hierarchical levels from right to left. Returns a list of tuples that can be passed directly to grouping_sets, or used with fixed columns in a nested list specification.
This matches SQL's GROUP BY ROLLUP(A, B), C syntax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*columns |
str
|
Column names in hierarchical order (left = highest level) |
()
|
Returns:
| Type | Description |
|---|---|
list[tuple[str, ...]]
|
list[tuple[str, ...]]: List of tuples representing ROLLUP hierarchy levels |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no columns are provided |
TypeError
|
If any column is not a string |
Example
from pyretailscience.segmentation import rollup
Simple ROLLUP - returns list of tuples
rollup("year", "quarter", "month") [("year", "quarter", "month"), ("year", "quarter"), ("year",), ()]
Use directly (equivalent to explicit list of tuples)
stats = SegTransactionStats( ... data=df, ... segment_col=["year", "quarter", "month"], ... grouping_sets=rollup("year", "quarter", "month") ... )
ROLLUP with fixed column - wrap in tuple
stats = SegTransactionStats( ... data=df, ... segment_col=["year", "quarter", "month", "store"], ... grouping_sets=[(rollup("year", "quarter", "month"), "store")] ... )
Produces 4 grouping sets (3+1 from ROLLUP):
[("year", "quarter", "month", "store"), ("year", "quarter", "store"),
("year", "store"), ("store",)]