Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MultiIndex column names and pandas styler alignment

In Jupyter, when displaying a dataframe with a multiIndex, the first level is left-aligned.

import numpy as np
cols = pd.MultiIndex.from_tuples([(x, y) for x in ['A', 'B', 'C'] for y in ['O', 'I']])
df = pd.DataFrame(np.random.randn(2, 6), index=['n', 'm'], columns=cols)
df

multiindex left-aligned

When displaying the same using pandas styler, it becomes right-aligned

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df.style

multiindex pandas styler right-aligned

Do you know how to control the alignment? Thank you.

>Solution :

I’m not sure why the difference is, but here’s a simple fix:

style = df.style.set_table_styles([
   {'selector': 'th',
    'props': [
        ('text-align', 'left')
    ]
    }]
)

style

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading