[Python] Column level alignment in pandas DataFrame printing

Discussão em 'Python' iniciado por Stack, Agosto 27, 2025.

  1. Stack

    Stack Membro Participativo

    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

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


    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


    Is there a way to get the second output?

    PS. As suggested by @mozway, RFE.

    Continue reading...

Compartilhe esta Página