admin管理员组

文章数量:1122832

How to add space between different groups when printing a pandas dataframe? The purpose is to separate different groups for improved visualization. Ideally both for column groups and row groups, also even for multi index groups.

Here I provide an image, on which arrows show an example spacing.

import pandas as pd

# Example DataFrame with MultiIndex
index = pd.MultiIndex.from_tuples([
    ('Group 1', 'Row 1'),
    ('Group 1', 'Row 2'),
    ('Group 2', 'Row 1')
], names=['Group', 'Subgroup'])

columns = pd.MultiIndex.from_tuples([
    ('Metric A', 'Sub A1'),
    ('Metric A', 'Sub A2'),
    ('Metric B', 'Sub B1')
], names=['Metric', 'Submetric'])

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pd.DataFrame(data, index=index, columns=columns)

print(df)

The output is:

Metric           Metric A        Metric B
Submetric          Sub A1 Sub A2   Sub B1
Group   Subgroup                         
Group 1 Row 1           1      2        3
        Row 2           4      5        6
Group 2 Row 1           7      8        9

We want to be able to add spacing like this for an improved look:

Metric           Metric A        | Metric B
Submetric          Sub A1 Sub A2 |   Sub B1
Group   Subgroup                 |         
Group 1 Row 1           1      2 |        3
        Row 2           4      5 |        6
---------------- ----------------+---------
Group 2 Row 1           7      8 |        9

We added spacing between groups, both on grouped columns and grouped indices.

I checked pandas styling documentation but it seems like this case isn't considered.

本文标签: pythonpandas dataframe styling to add space between different groupsStack Overflow