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
>Solution :
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'])
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}'