Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is the kind of output I am looking for

Reqd output

>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'])

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}'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading