Feature Type

  • [ ] Adding new functionality to pandas

  • [x] 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

Comment From: samruddhibaviskar11

Hi @sam-s ,

I’ve reproduced the current MultiIndex column alignment behavior as described in this issue.

My plan is to add a new display option: pd.set_option('display.multiindex_column_alignment', 'left' | 'right' | 'center')

Default will stay 'left' for backward compatibility. I’ll update the formatting logic in pandas/io/formats/format.py to support these modes and add tests in pandas/tests/io/formats/ to cover them.

Please let me know if this approach works so I can proceed.

Comment From: sam-s

My plan is to add a new display option: pd.set_option('display.multiindex_column_alignment', 'left' | 'right' | 'center')

Default will stay 'left' for backward compatibility. I’ll update the formatting logic in pandas/io/formats/format.py to support these modes and add tests in pandas/tests/io/formats/ to cover them.

lgtm!

Please let me know if this approach works so I can proceed.

Thank you! Best of luck!

Comment From: sam-s

Please note that your new option should play well with pd.set_option('display.colheader_justify', "left"): instead of the current

   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 to see something like

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

thank you!