Search code examples
pandasmulti-indexpandas-styles

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

df.style

multiindex pandas styler right-aligned

How can I control the alignment?


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