Flatbread is a small library which adds some pivot-table-like functionality to pandas. Flatbread can be accessed in DataFrames
and Series
using the pita
accessor.
Let's create a df for testing:
from random import randint
import pandas as pd
import flatbread as fb
df = pd._testing.makeCustomDataframe(
nrows=8,
ncols=4,
data_gen_f=lambda r,c:randint(1,100),
c_idx_nlevels=2,
r_idx_nlevels=3,
c_ndupe_l=[2,1],
r_ndupe_l=[4,2,1],
)
Flatbread let's you easily add totals and subtotals to your pivot tables:
df.pita.add_totals().pita.add_subtotals(axis=2, levels=0)
C0 | C_l0_g0 | C_l0_g1 | ||||||
---|---|---|---|---|---|---|---|---|
C1 | C_l1_g0 | C_l1_g1 | Subtotals | C_l1_g2 | C_l1_g3 | Subtotals | ||
R0 | R1 | R2 | ||||||
R_l0_g0 | R_l1_g0 | R_l2_g0 | 16.0 | 4.0 | 20.0 | 34.0 | 59.0 | 93.0 |
R_l2_g1 | 49.0 | 51.0 | 100.0 | 33.0 | 10.0 | 43.0 | ||
R_l1_g1 | R_l2_g2 | 10.0 | 46.0 | 56.0 | 43.0 | 82.0 | 125.0 | |
R_l2_g3 | 98.0 | 62.0 | 160.0 | 81.0 | 28.0 | 109.0 | ||
Subtotals | 173.0 | 163.0 | 336.0 | 191.0 | 179.0 | 370.0 | ||
R_l0_g1 | R_l1_g2 | R_l2_g4 | 99.0 | 17.0 | 116.0 | 50.0 | 99.0 | 149.0 |
R_l2_g5 | 17.0 | 91.0 | 108.0 | 51.0 | 36.0 | 87.0 | ||
R_l1_g3 | R_l2_g6 | 78.0 | 81.0 | 159.0 | 77.0 | 53.0 | 130.0 | |
Subtotals | 194.0 | 189.0 | 383.0 | 178.0 | 188.0 | 366.0 | ||
Totals | 367.0 | 352.0 | 719.0 | 369.0 | 367.0 | 736.0 |