Andy Jensen
Andy Jensen

Reputation: 93

Python: Pandas how to highlight the Header Row

Here is the function that highlights all the rows in my table:

def highlight(s): 
if s.Points == 10 or s.Points == 15:
    return ['background-color : #d9ead3']*3
elif s.Points == 8 or s.Points == 6:
    return ['background-color : #cfe2f3']*3
elif s.Points == 5:
    return ['background-color : #f4cccc']*3
elif s.Points == 4:
    return ['background-color : #fff2cc']*3
elif s.Points == 3:
    return ['background-color : #d9d2e9']*3
elif s.Points == 2:
    return ['background-color : #c9daf8']*3
elif s.Points == 1:
    return ['background-color : #ead1dc']*3
else:
    return ['background-color : white']*3

I then call that function like this:

dfnew = df.style.apply(highlight, axis = 1).set_table_styles([{'selector' : '', 
                        'props' : [('border', 
                                    '2px solid black')]}]).set_properties(**{'font-size':'11pt'}) 

I want to also highlight the Header row(Rank, GolferName, Points). How do i do that?

Here's what my table looks like:

enter image description here

Upvotes: 1

Views: 1606

Answers (1)

Mehdi Golzadeh
Mehdi Golzadeh

Reputation: 2583

Have you tried this?

col_loc_1 = df.columns.get_loc('Rank') + 2
col_loc_1 = df.columns.get_loc('GolferName') + 2

df.style.apply(highlight, axis = 1).set_table_styles(
     [{'selector': f'th:nth-child({col_loc_1})',
       'props': [('background-color', '#ff0')]},
     {'selector': f'th:nth-child({col_loc_1})',
       'props': [('background-color', '#00F')]}])

Upvotes: 2

Related Questions