1

I have a pandas dataframe and I want to style a particular column if the row contains a particular string. Here is the function is used and how I called it.

def color_code(value):
    match_b = re.search(r'\bball\b',value)
    match_c =re.search(r'\bcar\b',value)
    if match_b == True:
        color = 'red'
    elif match_c ==True:
        color = 'yellow'
    else:
        return
    return f'background-color: {color}'

res=df.applymap(color_code,subset['Interest'])

Assuming I have a column like this

Interest
coin
racecar
bumper-car
ball
beachball
volley ball
base-ball
bat
car
beach
nascar
remote car

I want the cell to be colored as long as the value contains ball or car, but I am not able to find a way to do so. I am only able to find ways to color the cell only if the value is exact as 'ball' or 'car'

This is the kind of output I am looking for

Reqd output

1
  • What is the output you want? Commented Feb 10, 2023 at 11:31

1 Answer 1

3

Remove word bouncaries \b\b:

def color_code(value):
    match_b = re.search(r'ball',value)
    match_c = re.search(r'car',value)
    
    if match_b:
        color = 'red'
    elif match_c:
        color = 'yellow'
    else:
        color='white'
    print (color)
    return f'background-color: {color}'

res=df.style.applymap(color_code,subset=['Interest'])

enter image description here

Or:

def color_code(value):
    if 'ball' in value:
        color = 'red'
    elif 'car' in value:
        color = 'yellow'
    else:
        color='white'
    print (color)
    return f'background-color: {color}'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This works perfectly. However, I want to export this to an excel file, when doing so all the other rows in that column are coloured black. So, I made the following change else: color='' to else: color='white' Hope, this helps anyone else if they have a similar issue in the future

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.