Search code examples
pythonpandascrosstab

change multi level index fonts with pandas style function


I want to make some nice tables with a multi-level index (cross-tabulated across multiple variables). With the data below, the indexes for place, band and status are rather large and in charge if i print it with pandas style function. Is there a way to change the size/colour/font of multi-level titles? many thanks in advance

df1 = pd.DataFrame(data={'id': [1,2,3,4,5,6,7,8,9,10], 'place': [1,1,2,2,2,1,1,2,1,1], 'band': [1,2,3,3,3,2,1,2,3,1], 'status': [1,2,2,1,1,1,1,2,1,2]})

d1={1: 'north', 2: 'south'} 
d2={1: '10-20', 2: '30-40', 3: '20-30'} 
d3={1: 'green', 2: 'red'} 

df1['place']=df1['place'].map(d1).fillna('Other')
df1['band']=df1['band'].map(d2).fillna('Other')
df1['status']=df1['status'].map(d3).fillna('Other')

tab = pd.crosstab(df1.band, [df1.place, df1.status]).apply(lambda r: r/r.sum(), axis=1).round(2) 

tab.style


Solution

  • You cannot decorate individual indexes in a multi-index, but you can take the following approach for a batch.

    th_css = [
        {
            "selector": "th",
            "props": [
                ("background-color", "#48d1cc"),
                ("color", "white"),
                ("border", "1px solid #fdf5e6"),
                ("font-size", "16px"),
            ],
        },
    ]
    style = tab.style
    style = style.set_precision(2).set_table_styles(th_css)
    style
    

    enter image description here