2

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

b101
  • 287
  • 1
  • 8
  • The style of the table is 'th' only, so it cannot be changed at the individual level. If you want to change the multi-index uniformly, you can set the original CSS to decorate it. I will answer if you want to use uniformity. – r-beginners Jun 08 '21 at 09:37
  • thanks for your response @r-beginners i would really appreciate that - that would be great – b101 Jun 08 '21 at 10:50

1 Answers1

2

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

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • thats really useful and great thank you! is there a way to make the font not bold? its so abrasive. or another way to make nice tables..thanks so much – b101 Jun 08 '21 at 14:49
  • If you add this, the text will no longer be bold. `("font-weight", "normal")` – r-beginners Jun 09 '21 at 01:37