7

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.

6
  • Unfortunately, this is not directly possible directly with pandas, nor with third-party libraries like tabulate. You can do this in HTML though. For strings, you probably will need a custom function. Maybe worth a feature request? Commented Aug 11 at 19:28
  • 4
    @mozway: github.com/pandas-dev/pandas/issues/62089 Commented Aug 11 at 19:46
  • Can confirm, this looks fine using the default HTML display in JupyterLab, VSC Jupyter, and Spyder Notebook. Commented Aug 17 at 13:15
  • maybe check out tabulate Commented Sep 9 at 11:23
  • @sds, now that you have the answer using pd.set_option('display.colheader_justify', "right"), do you want to close the question? Commented Sep 21 at 19:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.