1

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?

2 Answers 2

1

Use the in operator with a set membership test:

def Highlight_Majors(val):
    return 'color: %s' % ('blue' if val in {"Austria", "Belgium"} else 'black')
Sign up to request clarification or add additional context in comments.

Comments

0

How about this?

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

2 Comments

@prashanthmanohar Don't use this. It's really slow. I gave it a -1 because it is a bad way of testing. See my answer for details.
@coldspeed I assume downvote is meant for 'answer not useful' but in this case this approach could be just another way of achieving the same result. Thanks anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.