Skip to content

PitaFrame

flatbread.accessors.dataframe.PitaFrame

Bases: PitaDisplayMixin

Tabulation methods for DataFrames, registered as df.pita.

All methods return a new DataFrame, leaving the original unmodified. Methods can be chained.

add_agg(aggfunc, *, axis=0, label=None, ignore_keys=None, _fill='')

Add aggregation to df.

Parameters:

Name Type Description Default
aggfunc str | Callable

Function to use for aggregating the data.

required
axis Axis

Axis to aggregate. Default 0.

0
label str | None

Label for the aggregation row/column. Default None.

None
ignore_keys str | list[str] | None

Keys of rows to ignore when aggregating.

None

Returns:

Type Description
pd.DataFrame:

Table with aggregated rows/columns added.

Examples:

>>> df.pita.add_agg('mean')
>>> df.pita.add_agg('median', axis=1, label='Median')
>>> df.pita.add_agg(lambda x: x.max() - x.min(), label='range')

add_subagg(aggfunc, *, axis=0, level=0, label=None, include_level_name=False, ignore_keys=None, skip_single_rows=True, _fill='')

Add aggregation to specified levels of the df.

Parameters:

Name Type Description Default
aggfunc str | Callable

Function to use for aggregating the data.

required
axis Axis

Axis to aggregate. Default 0.

0
level int | str | list[int | str]

Levels to aggregate. Default 0.

0
label str | None

Label for the aggregation row/column. Default None.

None
include_level_name bool

Whether to add level name to subtotal label.

False
ignore_keys str | list[str] | None

Keys of rows to ignore when aggregating. Default 'Totals'

None
skip_single_rows bool

Whether to skip single rows when aggregating. Default True.

True

Returns:

Type Description
pd.DataFrame:

Table with aggregated rows/columns added.

Examples:

>>> df.pita.add_subagg('mean', level=0)
>>> df.pita.add_subagg('mean', level=0, include_level_name=True)

add_totals(axis=2, label=None, ignore_keys=None, _fill='')

Add totals to df.

Parameters:

Name Type Description Default
axis Axis

Axis to sum. If axis == 2 then add totals to both rows and columns. Default 2.

2
label str | None

Label for the totals row/column. Default 'Totals'.

None
ignore_keys str | list[str] | None

Keys of rows to ignore when aggregating. Default 'Subtotals'

None

Returns:

Type Description
pd.DataFrame:

Table with total rows/columns added.

Examples:

>>> df.pita.add_totals()  # adds to both rows and columns
>>> df.pita.add_totals(axis=0)  # row totals only
>>> df.pita.add_totals(axis=1, label='Sum')  # column totals with custom label

add_subtotals(axis=2, level=0, label=None, include_level_name=False, ignore_keys=None, skip_single_rows=True, _fill='')

Add subtotals to df.

Parameters:

Name Type Description Default
axis Axis

Axis to sum. If axis == 2 then add totals to both rows and columns. Default 2.

2
levels

Levels to sum with func. Default 0.

required
label str | None

Label for the subtotals row/column. Default 'Subtotals'.

None
include_level_name bool

Whether to add level name to subtotal label.

False
ignore_keys str | list[str] | None

Keys of rows to ignore when aggregating. Default 'Totals'

None
skip_single_rows bool

Whether to skip single rows when aggregating. Default True.

True

Returns:

Type Description
pd.DataFrame:

Table with total rows/columns added.

Examples:

>>> df.pita.add_subtotals(level=0)  # subtotals by outermost index level
>>> df.pita.add_subtotals(level=[0, 1])  # subtotals at multiple levels
>>> df.pita.add_subtotals(level=0, include_level_name=True)

sort_totals(axis=0, level=None, labels=None, totals_last=True, sort_remaining=True)

Sort index/columns to position totals and subtotals at start or end within groups.

Convenience function that sorts common aggregate labels (totals, subtotals) to their appropriate positions, while leaving other items in their existing order. Uses default labels from flatbread configuration unless custom labels are provided.

Parameters:

Name Type Description Default
axis Axis

Axis to sort along: - 0 or 'index': sort the index (rows) - 1 or 'columns': sort the columns

0
level Level | list[Level] | None

Index level(s) to sort. Can be level number(s), level name(s), or None for all levels.

None
labels list[str] | None

Custom labels to treat as totals/subtotals. If None, uses default labels from flatbread configuration ('Totals', 'Subtotals').

None
totals_last bool

Whether to place totals/subtotals at the end (True) or beginning (False) of each group.

True
sort_remaining bool

Whether to sort non-target levels alphabetically.

True

Returns:

Type Description
DataFrame

DataFrame with totals/subtotals repositioned according to the specified parameters.

as_percentages(axis=2, label_totals=None, ignore_keys=None, ndigits=None, base=1, apportioned_rounding=None)

Transform data to percentages based on specified axis.

Parameters:

Name Type Description Default
axis Axis

The axis along which percentages are calculated. Percentages are based on: - when axis is 2 then grand total - when axis is 1 then column totals - when axis is 0 then row totals Default is 2.

2
label_totals str | None

Label of the totals column/row. If no label is supplied then totals will be assumed to be either the last row, last column or last row/column field. Default is None.

None
ignore_keys str | list[str] | None

Keys of rows/columns to ignore when calculating percentages.

None
ndigits int | None

Number of decimal places to round the percentages. Default is -1 (no rounding).

None
base int

The whole quantity against which to calculate the fraction.

1

Returns:

Type Description
pd.DataFrame:

DataFrame with data transformed to percentages.

as_pct(*args, **kwargs)

Alias for :meth:as_percentages.

add_percentages(axis=2, label_n=None, label_pct=None, label_totals=None, ignore_keys=None, ndigits=None, base=1, apportioned_rounding=None, interleaf=False)

Add percentage columns to a DataFrame based on specified axis.

Parameters:

Name Type Description Default
axis Axis

The axis along which percentages are calculated. Percentages are based on: - when axis is 2 then grand total - when axis is 1 then row totals - when axis is 0 then column totals Default is 2.

2
label_n str | None

Label for the original count columns. Default is 'n'.

None
label_pct str | None

Label for the percentage columns. Default is 'pct'.

None
label_totals str | None

Label of the totals column/row. If no label is supplied then totals will be assumed to be either the last row, last column or last row/column field. Default is None.

None
ignore_keys str | list[str] | None

Keys of rows/columns to ignore when calculating percentages.

None
ndigits int | None

Number of decimal places to round the percentages. Default is -1 (no rounding).

None
base int

The whole quantity against which to calculate the fraction.

1
interleaf bool

If interleaf is True then percentages columns will be placed next to count columns. If set to False the percentages columns will have their own separate block in the table. Default is False.

False

Returns:

Type Description
pd.DataFrame:

DataFrame with additional columns for percentages.

Examples:

>>> df.pita.add_totals().pita.add_percentages()  # percentages of grand total
>>> df.pita.add_totals().pita.add_percentages(axis=0)  # column percentages
>>> df.pita.add_totals().pita.add_percentages(ndigits=1, base=100)
>>> df.pita.add_totals().pita.add_percentages(interleaf=True)

add_pct(*args, **kwargs)

Alias for :meth:add_percentages.

as_differences(axis=0, periods=1, method='diff')

Transform data to differences based on specified axis.

Parameters:

Name Type Description Default
periods int

Number of periods to shift.

1
method (diff, pct_change)

Differencing method to apply.

'diff'
axis (0, 1, index, columns)

Axis along which to compute diffs. 0 for rows, 1 for columns.

0
label_diff str

Label for the difference data.

required

Returns:

Type Description
DataFrame

Differenced data with consumed periods removed. Fewer rows (axis=0) or columns (axis=1) than the input.

as_diffs(*args, **kwargs)

Alias for :meth:as_differences.

add_differences(axis=0, periods=1, label_n='n', label_diff='diff', ignore_keys=None, interleaf=False)

Add differences alongside original DataFrame data.

Parameters:

Name Type Description Default
axis (0, 1, index, columns)

Axis along which to compute diffs.

0
periods int

Number of periods to shift.

1
label_n str

Label for the original data panel.

'n'
label_diff str

Label for the difference panel.

'diff'
interleaf bool

If True, interleave diff columns with their corresponding data columns instead of appending as a separate panel.

False
ignore_keys str or list[str] or None

Additional keys to exclude from diff computation. Keys from prior flatbread operations are excluded automatically.

None

Returns:

Type Description
DataFrame

Combined data with differences added. Adds one level to the column index to distinguish data from diffs.

Examples:

>>> df.pita.add_differences()
>>> df.pita.add_differences(axis=1, periods=2)
>>> df.pita.add_differences(interleaf=True)

add_diffs(*args, **kwargs)

Alias for :meth:add_differences.

add_pct_change(axis=0, *, label_n=None, label_pct_change=None, ignore_keys=None, periods=1, interleaf=False)

Add percentage change panel alongside original data.

Parameters:

Name Type Description Default
axis Axis

Axis along which to compute pct_change. Default 0.

0
label_n str or None

Label for the original data panel.

None
label_pct_change str or None

Label for the pct_change panel.

None
ignore_keys str or list[str] or None

Keys to exclude from computation.

None
periods int

Number of periods to shift.

1
interleaf bool

If True, interleave pct_change columns with data columns.

False

Returns:

Type Description
DataFrame

DataFrame with pct_change panel appended.

Examples:

>>> df.pita.add_pct_change()
>>> df.pita.add_pct_change(axis=1, periods=2)

export_excel(filepath, title=None, number_formats=None, border_specs=None, **kwargs)

Export DataFrame to Excel with automatic formatting based on flatbread configuration.

Parameters:

Name Type Description Default
filepath str | Path

Path to save the Excel file

required
title str

Title for the worksheet

None
number_formats dict

Custom number formats (overrides auto-detected ones)

None
border_specs dict

Custom border specifications (merged with margin borders)

None
**kwargs

Additional arguments passed to pandasxl WorksheetManager

{}

add_level(value, level=0, level_name=None, axis=0)

Add a level containing the specified value to a DataFrame axis.

Parameters:

Name Type Description Default
value Any

Value to fill the new level with.

required
level int

Position to insert the new level. Defaults to 0 (start).

0
level_name Any

Name for the new level. Defaults to None.

None
axis int

Axis to modify (0 for index, 1 for columns). Defaults to 0.

0

Returns:

Type Description
pd.DataFrame:

DataFrame with the new level added to the specified axis.

merge_levels(level_a, level_b, axis=0)

Merge two levels of a MultiIndex into one.

For each position, if one level's value is duplicated while the other's is unique, the unique value is kept. If both are unique (conflict), the value from level_a takes priority.

Parameters:

Name Type Description Default
level_a Level

First level (priority on conflict).

required
level_b Level

Second level.

required
axis Axis

Axis to modify (0 for index, 1 for columns).

0

Returns:

Type Description
DataFrame

DataFrame with the two levels merged into one.

interleave()

Interleave panel columns with data columns.

Returns:

Type Description
DataFrame

DataFrame with interleaved columns.

Raises:

Type Description
ValueError

If no panels exist, symmetric and asymmetric panels are mixed, or DataFrame is already interleaved.