prashanth manohar
prashanth manohar

Reputation: 680

Styling pandas based on conditions

I am trying to color the text or cells of data frame based on the condition. This is the code I have. It works:

def Highlight_Majors(val):

    color = 'blue' if val == "Austria" else 'black'
    return 'color: %s' % color

s = df.style.applymap(Highlight_Majors)
s

The string "Austria" now appears highlighted in the dataframe. What if I have more than one countries I need to highlight?

This does not work:

def Highlight_Majors(val):

    color = 'blue' if val == "Austria"|"Belgium" else 'black'
    return 'color: %s' % color

What is the right way to do it?

Upvotes: 1

Views: 971

Answers (2)

cs95
cs95

Reputation: 402483

Use the in operator with a set membership test:

def Highlight_Majors(val):
    return 'color: %s' % ('blue' if val in {"Austria", "Belgium"} else 'black')

Upvotes: 1

Prem
Prem

Reputation: 11955

How about this?

color = 'blue' if any([val==i for i in ["Austria", "Belgium"]]) else 'black'

Upvotes: 0

Related Questions