Skip to content

ENH: More compact printing of a DataFrame with MultiIndex columns #62089

@sam-s

Description

@sam-s

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

When a pandas DataFrame is printed, the MultiIndex column levels are aligned with the 1st (left most) column instead of the last (right most) column:

import numpy as np
import pandas as pd

print(pd.DataFrame(data=[np.arange(6),np.arange(6)+5], columns=pd.MultiIndex.from_product([("a"*10,"b"*20),("A","B","C")])))

produces

  aaaaaaaaaa       bbbbbbbbbbbbbbbbbbbb       
           A  B  C                    A  B   C
0          0  1  2                    3  4   5
1          5  6  7                    8  9  10

instead of the more compact (and, arguably, clearer and more natural)

        aaaaaaaaaa   bbbbbbbbbbbbbbbbbbbb       
           A  B  C               A  B   C
0          0  1  2               3  4   5
1          5  6  7               8  9  10

It would be nice if the second version were available, at least as an option.

Feature Description

Level values in MultiIndex columns should align with the right-most relevant lower-level column.

This may be controlled by a pd.set_option('display.multiindex_column_alignment', 'right') - proposed behavior vs left - current behavior. Additional value can be "center". Or first instead of left and last instead of right.

Alternative Solutions

none

Additional Context

Column level alignment in pandas DataFrame printing

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementNeeds TriageIssue that has not been reviewed by a pandas team memberOutput-Formatting__repr__ of pandas objects, to_string

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions