Styling column/columns in pandas if it contains a certain string

Question:

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'bballb',value)
    match_c =re.search(r'bcarb',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

Asked By: Marvin

||

Answers:

Remove word bouncaries bb:

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}'
Answered By: jezrael
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.