Repository navigation
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
3847 lines (3418 loc) · 123 KB
/
Copy pathstreamlit_app.py
File metadata and controls
3847 lines (3418 loc) · 123 KB
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
# Copyright 2025 Snowflake Inc.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Streamlit Pivot Table — Feature Documentation & Examples
Community Cloud entry point. Also runnable locally:
streamlit run streamlit_app.py
"""
import datetime as _dt
import random as _rnd
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from streamlit_pivot import st_pivot_table, PivotStyle, RegionStyle, PIVOT_STYLE_PRESETS
import streamlit as st
st.set_page_config(page_title="Pivot Table — Feature Guide", layout="wide")
st.title("Streamlit Pivot Table — Feature Guide")
st.caption(
"Each section below demonstrates a cohort of features with its own pivot table. "
"Interact with the tables to explore the functionality described."
)
_DATA_DIR = Path(__file__).parent / "tests" / "golden_data"
df = pd.read_csv(_DATA_DIR / "small.csv")
df_medium = pd.read_csv(_DATA_DIR / "medium.csv")
df_field_search = df_medium.assign(
Cost=(df_medium["Revenue"] - df_medium["Profit"]).round(2),
RevenuePerUnit=(df_medium["Revenue"] / df_medium["Units"]).round(2),
DiscountAmount=(df_medium["Revenue"] * df_medium["Discount"]).round(2),
ProfitMargin=(df_medium["Profit"] / df_medium["Revenue"]).round(3),
)
_rnd.seed(42)
_date_regions = ["US", "EU", "APAC"]
_date_base = {
"US": [120, 110, 135, 150, 160, 175, 190, 185, 170, 155, 140, 130],
"EU": [90, 85, 100, 115, 125, 140, 150, 145, 130, 120, 105, 95],
"APAC": [70, 65, 80, 95, 105, 120, 130, 125, 110, 100, 85, 75],
}
_date_records = []
for year in [2023, 2024]:
for month_idx in range(12):
for region in _date_regions:
base = _date_base[region][month_idx]
growth = 1.08 if year == 2024 else 1.0
rev = int(base * growth + _rnd.randint(-10, 10))
d = _dt.date(year, month_idx + 1, 1)
_date_records.append(
{
"region": region,
"order_date": d,
"ship_date": d + _dt.timedelta(days=3),
"Revenue": rev,
}
)
df_dates = pd.DataFrame(_date_records)
# ---------------------------------------------------------------------------
# Section 1: Getting Started — Basic Pivot
# ---------------------------------------------------------------------------
st.divider()
st.subheader("1. Getting Started — Basic Pivot")
@st.fragment
def section_basic():
st.markdown(
"""
A basic pivot table needs three things: **row dimensions**, **column dimensions**,
and **value fields** to aggregate.
**Try it:**
- Click the **Settings** icon in the toolbar utility menu to open the **Settings Panel**
— this is the primary surface for adding, removing, and rearranging fields.
Make changes, then click **Apply** (or **Cancel** / Escape to discard).
- Omit `rows`, `columns`, and `values` entirely to let the component auto-detect dimensions and measures.
- Click any data cell — the cell coordinates will appear below the table.
- Hover over the top-right of the toolbar to reveal the **utility menu**:
- **Reset** (↺) — resets the config to the original Python-supplied values
(only visible when the config has been changed).
- **Swap** (↔) — transposes row and column dimensions.
- **Copy Config** — copies the current config as JSON to your clipboard.
- **Import Config** — paste a JSON config to apply it.
- **Export Data** (↓) — export the table as Excel, CSV, TSV, or copy to clipboard
(see Section 12 for details).
- **Settings** — opens the full Settings Panel for field configuration,
aggregation, synthetic measures, and display toggles (see Section 19).
"""
)
st_pivot_table(
df,
key="basic",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
aggregation="sum",
show_totals=True,
interactive=True,
on_cell_click=lambda: None,
)
with st.expander("View Code"):
st.code(
"""
st_pivot_table(
df,
key="basic",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
aggregation="sum",
show_totals=True,
interactive=True,
)
""",
language="python",
)
basic_cell_click = st.session_state.get("basic", {}).get("cell_click")
if basic_cell_click:
st.info(f"Last cell click: {basic_cell_click}")
st.markdown("#### Auto-Detect Layout")
st.markdown(
"""
If you omit `rows`, `columns`, and `values`, the component auto-detects dimensions
and measures from the input data. This is useful for quick exploration when you
want a sensible starting layout without pre-configuring the pivot.
"""
)
st_pivot_table(
df,
key="basic_auto_detect",
)
st.markdown("#### Field Search in Settings Panel")
st.markdown(
"""
When the Settings Panel has more than **8 available fields**, a search input
appears at the top of the **Available Fields** section. This wider demo includes
enough dimensions and numeric measures to surface the search.
**Try it:**
- Open the **Settings Panel** (pivot icon) and type part of a field name in the
search box above the Available Fields chips.
- The chip list filters in place while the container maintains its original height.
"""
)
st_pivot_table(
df_field_search,
key="basic_field_search",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
interactive=True,
show_totals=True,
)
section_basic()
# ---------------------------------------------------------------------------
# Section 2: Multiple Measures and Sorting
# ---------------------------------------------------------------------------
st.divider()
st.subheader("2. Multiple Measures and Sorting")
@st.fragment
def section_sorting():
st.markdown(
"""
Add multiple value fields to compare measures side-by-side. Sorting lets you
rank rows or columns by label or by value.
**Try it:**
- The table shows both **Revenue** and **Profit** — notice the value label row
below the column headers.
- Open the **Settings Panel** (pivot icon) to see the Values zone with each
measure's aggregation control (click the badge, e.g. "Sum", to change it).
- Notice the toolbar value chips use a compact inline format like
**Revenue (Sum)**.
- Click the **⋮** menu icon on a row/column header to open the **header menu**.
Choose **Sort A→Z**, **Sort Z→A**, or **Sort by value ↑/↓**.
- When sorting by value, pick which measure and which column to sort against.
**API parameters used:** `row_sort`, `col_sort`
"""
)
st_pivot_table(
df,
key="sorting",
rows=["Region"],
columns=["Year"],
values=["Revenue", "Profit"],
aggregation={"Revenue": "sum", "Profit": "avg"},
row_sort={"by": "value", "direction": "desc", "value_field": "Revenue"},
col_sort={"by": "key", "direction": "asc"},
)
with st.expander("View Code"):
st.code(
"""
st_pivot_table(
df,
key="sorting",
rows=["Region"],
columns=["Year"],
values=["Revenue", "Profit"],
aggregation={"Revenue": "sum", "Profit": "avg"},
row_sort={"by": "value", "direction": "desc", "value_field": "Revenue"},
col_sort={"by": "key", "direction": "asc"},
)
""",
language="python",
)
section_sorting()
# ---------------------------------------------------------------------------
# Section 3: Filtering, Locked Mode, and Non-Interactive Mode
# ---------------------------------------------------------------------------
st.divider()
st.subheader("3. Filtering, Locked Mode, and Non-Interactive Mode")
@st.fragment
def section_filtering():
st.markdown(
"""
Control which values appear via **header menu filters** or the Python API.
**Locked mode** freezes the toolbar config controls so end-users cannot change
rows, columns, values, or per-measure aggregation — but sorting and filtering via header
menus still work, **Show Values As** remains available on value headers, and
export still stays available as a viewer action. **Custom sorters** enforce a specific dimension order.
**Non-interactive mode** (`interactive=False`) is the true read-only mode:
the toolbar is hidden, header-menu config actions are disabled, but cell clicks
and drill-down still work.
**Try it (left table):**
- Click the **⋮** menu icon on the "Region" header → uncheck regions to filter them out.
- Use the search box to find specific values quickly.
**Middle table** is **locked** — authoring actions like reset, swap, and config import/export
are hidden, but **Export Data** remains available, and you can
still sort, filter, and change **Show Values As** from the header menus.
**Right table** is **non-interactive** — there is no toolbar and no header-menu
config UI, but cell clicks still work and drill-down remains enabled.
**API parameters used:** `hidden_from_aggregators`, `sorters`, `locked`, `interactive`
"""
)
col_left, col_middle, col_right = st.columns(3)
with col_left:
st.caption("Interactive (with custom sorters)")
st_pivot_table(
df,
key="filtering",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
sorters={"Region": ["North", "South", "East", "West"]},
null_handling="zero",
)
with col_middle:
st.caption("Locked mode")
st_pivot_table(
df,
key="locked",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue", "Profit"],
locked=True,
hidden_from_aggregators=["Year", "Region"],
show_subtotals=True,
)
with col_right:
st.caption("Non-interactive mode")
st_pivot_table(
df,
key="noninteractive",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
interactive=False,
on_cell_click=lambda: None,
)
with st.expander("View Code"):
st.code(
"""
# Interactive with custom dimension ordering
st_pivot_table(
df,
key="filtering",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
sorters={"Region": ["North", "South", "East", "West"]},
null_handling="zero",
)
# Locked — users cannot change configuration
st_pivot_table(
df,
key="locked",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue", "Profit"],
locked=True,
hidden_from_aggregators=["Year", "Region"],
show_subtotals=True,
)
# Non-interactive — no toolbar or header-menu config actions
st_pivot_table(
df,
key="noninteractive",
rows=["Region"],
columns=["Year"],
values=["Revenue"],
interactive=False,
on_cell_click=lambda: None,
)
""",
language="python",
)
noninteractive_cell_click = st.session_state.get("noninteractive", {}).get(
"cell_click"
)
if noninteractive_cell_click:
st.info(f"Non-interactive cell click: {noninteractive_cell_click}")
section_filtering()
# ---------------------------------------------------------------------------
# Section 4: Subtotals and Grouping
# ---------------------------------------------------------------------------
st.divider()
st.subheader("4. Subtotals and Grouping")
@st.fragment
def section_subtotals():
st.markdown(
"""
When you have **two or more row dimensions**, enable subtotals to see
aggregated values at each group level.
**Try it:**
- Each **Region** group has a subtotal row (e.g. "North Total") with a
**collapse/expand toggle** (+/−).
- Click the toggle to collapse a group — its child rows are hidden but the
subtotal stays visible.
- **Dimension-level collapse:** Click the **dimension header** label (e.g.
"Region ›") to collapse or expand **all groups at that level** at once.
This is available on both row and column headers when there are 2+ dimensions.
- Use the **Expand All** / **Collapse All** buttons in the toolbar utility menu.
- Open the **Settings Panel** (pivot icon) and toggle **Subtotals** and
**Repeat Labels** checkboxes, then click **Apply**.
**API parameters used:** `show_subtotals`, `repeat_row_labels`
"""
)
st_pivot_table(
df,
key="subtotals",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue"],
aggregation="sum",
show_subtotals=True,
repeat_row_labels=False,
)
with st.expander("View Code"):
st.code(
"""
st_pivot_table(
df,
key="subtotals",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue"],
show_subtotals=True,
repeat_row_labels=False,
)
""",
language="python",
)
st.markdown("#### Per-Dimension Subtotals")
st.markdown(
"""
Pass a list of dimension names to `show_subtotals` to control which levels get subtotal rows.
Only listed dimensions will have subtotals; others are skipped.
"""
)
st_pivot_table(
df_medium,
key="demo_per_dim_subtotals",
rows=["Region", "Category", "Product"],
columns=["Year"],
values=["Revenue", "Profit"],
show_subtotals=["Region"],
)
st.markdown("#### Per-Measure Row Totals")
st.markdown(
"""
Pass a list of measure names to `show_row_totals` to control which measures appear
in the rightmost Total column. Excluded measures show `–` (dash).
"""
)
st_pivot_table(
df,
key="demo_per_measure_row_totals",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue", "Profit"],
show_row_totals=["Revenue"],
)
st.markdown("#### Per-Measure Column Totals")
st.markdown(
"""
Pass a list of measure names to `show_column_totals` to control which measures appear
in the Grand Total row. Excluded measures show `–` (dash) in the Grand Total.
Subtotals are independent — they still show all measures regardless of this setting.
"""
)
st_pivot_table(
df_medium,
key="demo_per_measure_col_totals",
rows=["Region", "Category", "Product"],
columns=["Year"],
values=["Revenue", "Profit"],
show_column_totals=["Revenue"],
show_subtotals=True,
)
section_subtotals()
# ---------------------------------------------------------------------------
# Section 5: Aggregation and Show Values As
# ---------------------------------------------------------------------------
st.divider()
st.subheader("5. Aggregation and Show Values As")
@st.fragment
def section_aggregators():
st.markdown(
"""
Beyond Sum, Average, Count, Min, Max — the component supports **advanced
aggregators**: Count Distinct, Median, Percentile (90th), First, and Last.
**Show Values As** lets you display measures as **% of Grand Total**,
**% of Row Total**, or **% of Column Total** instead of raw numbers.
**Try it:**
- Open the **Settings Panel** (pivot icon) and click the aggregation badge on a
value chip to switch between Sum, Average, Count, Min, Max, and advanced
aggregators like Median, Percentile 90, Count Distinct, First, Last.
- Selected value chips show aggregation inline, using the same name-first
pattern as **Revenue (Sum)**.
- Click the **⋮** menu icon on a **value label** header (e.g. "Revenue") to open
its **Display** menu. Choose between Raw Value, % of Grand Total, % of Row
Total, or % of Column Total.
- When a % mode is active, a small **%** badge appears on the toolbar chip.
**API parameters used:** `aggregation`, `show_values_as`
"""
)
st_pivot_table(
df,
key="advanced_agg",
rows=["Region"],
columns=["Year"],
values=["Revenue", "Profit"],
aggregation="sum",
show_values_as={"Revenue": "pct_of_total"},
)
with st.expander("View Code"):
st.code(
"""
st_pivot_table(
df,
key="advanced_agg",
rows=["Region"],
columns=["Year"],
values=["Revenue", "Profit"],
aggregation="sum",
show_values_as={"Revenue": "pct_of_total"},
)
""",
language="python",
)
section_aggregators()
# ---------------------------------------------------------------------------
# Section 5 continued: Show Values As — Analytical Modes (0.5.0)
# ---------------------------------------------------------------------------
@st.fragment
def section_show_values_as_analytical():
st.markdown("#### Analytical Modes (0.5.0+)")
sva_df = pd.DataFrame(
{
"Region": ["US", "US", "US", "EU", "EU", "EU", "APAC", "APAC", "APAC"],
"Product": [
"Widget",
"Gadget",
"Doohickey",
"Widget",
"Gadget",
"Doohickey",
"Widget",
"Gadget",
"Doohickey",
],
"Quarter": [
"Q1",
"Q1",
"Q1",
"Q1",
"Q1",
"Q1",
"Q1",
"Q1",
"Q1",
],
"Revenue": [120, 80, 40, 200, 150, 50, 90, 60, 30],
}
)
st.markdown(
"""
**0.5.0** adds five new analytical **Show Values As** modes, accessible via the
**⋮** menu on a value header or via the `show_values_as` API parameter:
| Mode | Description |
|---|---|
| `running_total` | Cumulative sum along the row axis; resets per parent group |
| `pct_running_total` | Running total ÷ parent-group total for the same column |
| `rank` | Competition rank (1, 1, 3) per column, per parent group |
| `pct_of_parent` | Cell ÷ immediate parent subtotal |
| `index` | Excel INDEX formula: `cell × grand_total / (row_total × col_total)` |
The example below shows **running total** by product within each region.
**Totals and subtotals always display raw aggregates** — a running total at a
subtotal equals the subtotal itself, so transforming it would be misleading.
"""
)
col1, col2 = st.columns(2)
with col1:
st.caption("Running Total")
st_pivot_table(
sva_df,
key="sva_running_total",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
show_values_as={"Revenue": "running_total"},
)
with col2:
st.caption("% of Parent Subtotal")
st_pivot_table(
sva_df,
key="sva_pct_of_parent",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
show_values_as={"Revenue": "pct_of_parent"},
)
with st.expander("View Code"):
st.code(
"""
# Running total — resets per Region group
st_pivot_table(
df,
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
show_values_as={"Revenue": "running_total"},
)
# % of Parent — each Product ÷ its Region subtotal
st_pivot_table(
df,
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
show_values_as={"Revenue": "pct_of_parent"},
)
""",
language="python",
)
section_show_values_as_analytical()
# ---------------------------------------------------------------------------
# Section 6: Top N / Value Filters (0.5.0)
# ---------------------------------------------------------------------------
st.divider()
st.subheader("6. Top N / Bottom N and Value Filters")
@st.cache_data
def _section_filters_data():
import pandas as pd
import numpy as np
rng = np.random.default_rng(42)
regions = ["North", "South", "East", "West", "Central"]
products = [
"Widget A",
"Widget B",
"Widget C",
"Gadget X",
"Gadget Y",
"Gadget Z",
"Tool 1",
"Tool 2",
"Tool 3",
"Tool 4",
]
quarters = ["Q1 2024", "Q2 2024", "Q3 2024", "Q4 2024"]
rows = []
for region in regions:
for product in products:
for quarter in quarters:
revenue = int(rng.integers(50_000, 500_000))
rows.append(
{
"Region": region,
"Product": product,
"Quarter": quarter,
"Revenue": revenue,
}
)
return pd.DataFrame(rows)
def section_top_n_value_filters():
df = _section_filters_data()
col1, col2 = st.columns(2)
with col1:
st.markdown(
"""
**Top N / Bottom N** filters hide dimension members outside the top (or bottom) N
ranked by a measure. Ranking is **per-parent**: for a two-level hierarchy like
`[Region, Product]`, "Top 3 Products by Revenue" keeps the 3 highest-revenue
products **within each Region** independently.
The `top_n_filters` parameter accepts a list of dicts with keys:
- `field` — dimension to filter
- `n` — how many members to keep
- `direction` — `"top"` or `"bottom"`
- `by` — measure to rank by
- `axis` — `"rows"` or `"columns"` (default `"rows"`)
> ⚠️ Grand totals and subtotals always reflect **all data**, not just visible
> members. This is a deliberate product choice (simpler, avoids re-aggregation
> cost). The table shows a footnote to communicate this.
**Interactive**: open any row-dimension header menu to set a Top N or value
filter without code.
"""
)
with col2:
st.markdown(
"""
**Value Filters** suppress dimension members whose aggregated measure fails a
predicate at the grand-total column context. Evaluation is also **per-parent**.
The `value_filters` parameter accepts dicts with:
- `field` — dimension to filter
- `by` — measure to evaluate
- `operator` — `"gt"`, `"gte"`, `"lt"`, `"lte"`, `"eq"`, `"neq"`, `"between"`
- `value` — threshold (lower bound for `"between"`)
- `value2` — upper bound (required for `"between"`)
- `axis` — `"rows"` or `"columns"` (default `"rows"`)
Members with a **null** aggregated measure fail all predicates and are excluded.
**Hint**: these filters are also accessible via the column header ⋮ menu
("Top / Bottom N" and "Filter by value" sections) — no code required.
"""
)
st.markdown("##### Top 3 Products by Revenue per Region")
st.caption(
"50 products × 5 regions; only the top 3 revenue products per region are shown. "
"Grand totals include all products."
)
from streamlit_pivot import st_pivot_table
st_pivot_table(
df,
key="demo_top3_products",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
number_format={"Revenue": "$,.0f"},
top_n_filters=[
{"field": "Product", "n": 3, "by": "Revenue", "direction": "top"}
],
)
st.markdown("##### Revenue > $1M (annual total) — Value Filter")
st.caption(
"Products whose total annual Revenue ≤ $1M are hidden within each Region."
)
st_pivot_table(
df,
key="demo_value_filter_revenue",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
number_format={"Revenue": "$,.0f"},
value_filters=[
{"field": "Product", "by": "Revenue", "operator": "gt", "value": 1_000_000}
],
)
st.markdown("##### Bottom 2 Products per Region")
st.caption(
"Bottom 2 products by revenue within each region — useful for identifying "
"underperformers."
)
st_pivot_table(
df,
key="demo_bottom2_products",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
number_format={"Revenue": "$,.0f"},
top_n_filters=[
{"field": "Product", "n": 2, "by": "Revenue", "direction": "bottom"}
],
)
with st.expander("Code", expanded=False):
st.code(
"""\
from streamlit_pivot import st_pivot_table
# Top 3 Products by Revenue per Region
st_pivot_table(
df,
key="top3",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
top_n_filters=[
{"field": "Product", "n": 3, "by": "Revenue", "direction": "top"}
],
)
# Products with Revenue > $1M (per-region grand-total column context)
st_pivot_table(
df,
key="gt1m",
rows=["Region", "Product"],
columns=["Quarter"],
values=["Revenue"],
value_filters=[
{"field": "Product", "by": "Revenue", "operator": "gt", "value": 1_000_000}
],
)
""",
language="python",
)
section_top_n_value_filters()
# ---------------------------------------------------------------------------
# Section 7: Multi-field Sorting + Subtotal Position (0.5.0)
# ---------------------------------------------------------------------------
st.divider()
st.subheader("7. Multi-field Sorting + Subtotal Position")
@st.fragment
def section_sort_and_subtotals():
st.markdown(
"""
**Multi-field sorting** lets you chain sort criteria: the primary sort orders
rows/columns, and the secondary (tertiary, …) kicks in only when values are
equal, guaranteeing a deterministic, stable order.
**Subtotal position** (`"top"` or `"bottom"`) controls whether subtotal rows
appear as group *headers* (above members) or group *footers* (after members,
the default — matching Excel's default pivot behavior).
| Feature | Parameter | Default |
|---------|-----------|---------|
| Multi-field row sort | `row_sort=[{…}, {…}]` | single sort |
| Multi-field column sort | `col_sort=[{…}, {…}]` | single sort |
| Subtotal placement | `subtotal_position` | `"bottom"` |
**API parameters used:** `row_sort` (list), `subtotal_position`
"""
)
import pandas as pd # noqa: PLC0415
sort_data = pd.DataFrame(
{
"Region": ["East"] * 4 + ["West"] * 4,
"Category": ["Electronics", "Furniture", "Electronics", "Furniture"] * 2,
"Year": ["2023", "2023", "2024", "2024"] * 2,
"Revenue": [500, 500, 700, 300, 600, 200, 800, 400],
"Units": [10, 20, 14, 6, 12, 4, 16, 8],
}
)
st.markdown("##### Multi-field Sort: Primary Revenue desc, Secondary Category asc")
st.caption(
"East/2024 and West/2024 rows have different revenues so primary sort orders "
"them. Rows with equal revenue (East/2023 Electronics = West/2023 Electronics "
"= 500 and 600) fall back to Category asc for a stable, deterministic order."
)
st_pivot_table(
sort_data,
key="demo_multi_sort",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue", "Units"],
row_sort=[
{
"by": "value",
"direction": "desc",
"dimension": "Region",
"value_field": "Revenue",
},
{"by": "key", "direction": "asc", "dimension": "Category"},
],
show_subtotals=True,
number_format={"Revenue": "$,.0f"},
)
subtotal_data = pd.DataFrame(
{
"Region": ["East", "East", "East", "West", "West", "West"],
"Category": ["Electronics", "Furniture", "Clothing"] * 2,
"Revenue": [400, 300, 200, 350, 450, 150],
}
)
col1, col2 = st.columns(2)
with col1:
st.markdown("##### Subtotals at Bottom (default)")
st.caption("Subtotal row appears after group members — Excel default behavior.")
st_pivot_table(
subtotal_data,
key="demo_subtotal_bottom",
rows=["Region", "Category"],
columns=[],
values=["Revenue"],
show_subtotals=True,
subtotal_position="bottom",
number_format={"Revenue": "$,.0f"},
)
with col2:
st.markdown("##### Subtotals at Top")
st.caption(
"Subtotal row appears before group members — acts as a collapsible "
"group header."
)
st_pivot_table(
subtotal_data,
key="demo_subtotal_top",
rows=["Region", "Category"],
columns=[],
values=["Revenue"],
show_subtotals=True,
subtotal_position="top",
number_format={"Revenue": "$,.0f"},
)
with st.expander("Code", expanded=False):
st.code(
"""\
# Multi-field sorting
st_pivot_table(
df,
key="demo_multi_sort",
rows=["Region", "Category"],
columns=["Year"],
values=["Revenue"],
row_sort=[
{"by": "value", "direction": "desc", "dimension": "Region", "value_field": "Revenue"},
{"by": "key", "direction": "asc", "dimension": "Category"}, # breaks ties
],
)
# Subtotals at top (group headers)
st_pivot_table(
df,
key="demo_subtotal_top",
rows=["Region", "Category"],
values=["Revenue"],
show_subtotals=True,
subtotal_position="top",
)
""",
language="python",
)
section_sort_and_subtotals()
# ---------------------------------------------------------------------------
# Section 8: Values Axis Placement (0.5.0)
# ---------------------------------------------------------------------------
st.divider()
st.subheader("8. Values Axis Placement")
@st.fragment
def section_values_axis():
st.markdown(
"""
By default, multiple value fields appear as a **"Σ Values"** column-group in the
column headers — each column slot is repeated once per measure. Setting
`values_axis="rows"` moves measures onto the **row axis** instead: each
dimension row is split into one sub-row per measure, and a **Values** header
column labels each measure.
This layout mirrors how financial statements (income statements, balance sheets)
and accounting reports are typically presented — rows for line items, columns
for time periods.
| Feature | Parameter | Default |
|---------|-----------|---------|
| Place measures on rows | `values_axis="rows"` | `"columns"` |
| Incompatible with | period comparison `show_values_as`, temporal hierarchies | — |
**API parameter:** `values_axis`
"""
)
import pandas as pd # noqa: PLC0415
# --- Example 1: side-by-side comparison ---
st.markdown("##### Side-by-side: Values on Columns vs. Values on Rows")
st.caption(
"Both tables show the same data. On the left, Revenue and Units share "
"column slots (the default). On the right, each metric occupies its own row."
)
cmp_data = pd.DataFrame(
{
"Region": ["East", "East", "West", "West"],
"Category": ["Electronics", "Furniture", "Electronics", "Furniture"],
"Year": ["2023", "2024", "2023", "2024"],
"Revenue": [500, 700, 600, 800],