SSB flextab

PyPI Status Python Version License

Documentation Tests Coverage Quality Gate Status

pre-commit Black Ruff Poetry

Features

Flextab is a Python package for making flexible tabulation. It is made with Claude AI, models Sonnet 4.5 and Sonnet 5.

Flextab is inspired by the Sas procedure proc tabulate which again was based on the tpl language

It makes flexible tables in two dimensions, rows an columns, based on Pandas dataframes.

Requirements

  • pandas

  • numpy

  • openpyxl when exporting tables to Excel

Installation

You can install SSB flextab via pip from PyPI:

pip install ssb-flextab

Usage

Import pandas and flextab.

import pandas as pd
from ssb_flextab import flextab

Demo dataframe.

df = pd.DataFrame({
    "sex":        ["1", "1", "2", "1", None, "2", "2", "1", "2", "2"],
    "age_group":  ["2", "1", "2", "3", "1", "2", "2", "2", "3", None],
    "region":     [None, "2", "1", "2", "2", "3", "3", "2", "2", "1"],
    "education":  ["3", "2", "3", "1", "3", "3", "3", "1", "3", "2"],
    "income":     [300, 100, 450, 200, 650, 750, None, 850, 400, 350],
    "tax":        [100, 10, 200, 90, 340, 370, 30, None, 150, 150],
    "weight":     [1.5, 3.2, 1.7, 2.2, 6.1, 4.2, 1.9, 4.8, None, 8.2],
})

Two dimensions with totals at the top/left.

flextab(
    data=df,
    groupby=["region", "sex"],
    table="""
    total region
    ,
    total sex
    """
)

Nested columns in the row and column dimensions with sub-totals.

flextab(
    data=df,
    groupby=["region", "sex", "age_group", "education"],
    table="""
    total region * (total age_group)
    ,
    total sex * (total education)
    """
)

Stacked columns in the row dimension and introduction of measure columns with different statsistics.

flextab(
    data=df,
    groupby=["region", "sex", "age_group"],
    measure="income",
    table="""
    total region age_group
    ,
    income * (count sum mean) * (total sex)
    """
)

Different percentages:

  • Percentage of grand total

  • Row percentages

  • Column percentages

The cells in the table are formatted with one decimal and decimal comma.

flextab(
    data=df,
    groupby=["region", "sex"],
    table="""
    total region
    ,
    (pctn rowpctn colpctn) *format=7,1 * (total sex)
    """
)

A comprehensive tutorial is found in the docs folder at the Statistics Norway github pages.

Contributing

Contributions are very welcome. To learn more, see the Contributor Guide.

License

Distributed under the terms of the MIT license, SSB flextab is free and open source software.

Issues

If you encounter any problems, please file an issue along with a detailed description.

Credits

This project was generated from Statistics Norway’s SSB PyPI Template.