Search code examples
pythonpandasdataframepandas-styles

How can I chain the conditions for style functions in pandas?


That's what I want to achieve

I do have a Pandas Dataframe - e.g. this one:

            0           1           2
0  110.718803  119.821042  -52.593518
1   65.180254   33.518722  -69.893688
2 -135.652788  -64.711718 -241.717819
3  237.781393  -56.865142   15.969767
4  141.585158  138.904568 -115.155063
5   10.030938  -59.274415   73.328127
6  106.937681   -3.604859   44.418938
7  -49.478211  -91.574908  160.340627
8  170.744019  -85.764809  246.141857
9  -94.246832   81.069700 -113.460438

Based on 3 conditions the background-color of the cell should be different:
cell <= 0 should be in red
cell >= 100 should be in blue
all other cells

That's what I did to achieve that

I wrote this function (based on the infos in Pandas documentation Pandas styling:

def highlight_number(row):
    return [
        'background-color: red; color: white' if cell <= 0
        else 'background-color: green; color: white'
        for cell in row
    ]


df.style.apply(highlight_number)

it works fine for two conditions.

That's my problem

I tried different methods to add the third condition into the function above but I always got back an error.
Could you please give me a hint how to add the condition inside the list?
I didn't find an answer. Thx a lot.


Solution

  • You can write a normal for loop instead of list comprehension.

    def highlight_number(row):
        arr = []
        for cell in row:
            if  cell <= 0:
                arr.append('background-color: red; color: white')
            elif cell >= 100:
                arr.append('background-color: blue; color: white')
            else:
                arr.append('background-color: white; color: black')
        return arr
    df.style.apply(highlight_number)
    

    Output:

    enter image description here