How to color a cell in python if it contains a specific character?

Viewed 1272

I am working on a dataframe (from an excel-file) and i would like to format the cells.

The DF has following content (as example):

a b c
234 --> 500 200 --> 500 0
234 --> 500 400 6
66 34 1

I would like to color the cells that contain "-->" red. Any suggestions? I know Pandas has a styling function, but i cant find anything that helps me with my problem.

2 Answers

You can modify color_negative_red function for test if exist subtring by in:

def make_your_style(val):
    """
    Takes a scalar and returns a string with
    the css property `'background-color: red'` for string with -->
    """
    color = 'red' if '-->' in str(val) else ''
    return f'background-color: {color}'

df.style.applymap(make_your_style)

img

For write to excel use:

df.style.applymap(make_your_style).to_excel(file, engine='openpyxl', index=False)

When you are concerned with formatting your Pandas DataFrame, the usual procedure is defining one (or multiple) style functions where you define the CSS properties and then DF.style.applymap(style_function) these to your DataFrame.
The conditional formatting can take place either in the style function (as in this example) or by filtering your DataFrame and applying the style_function on the resulting subset!

# Function that specifies CSS

def color_fill(val):
    if "-->" in val:
        styling = 'background-color: red; color:black'
    return styling 

df = df.style.applymap(color_fill)
Related