Home > Back-end >  MultiIndex column names and pandas styler alignment
MultiIndex column names and pandas styler alignment

Time:03-23

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, however:

df.style

multiindex pandas styler right-aligned

How can I control the alignment?

CodePudding user response:

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

  • Related