Search code examples
pythonpandasstyleshighlightintervals

two intervals color df panda red <-3 and green >3


I would like to know how to generate two intervals for my highlight. I want all the value of my df <-3 in red and all the value >3 in green, else don't change, in black.

I try with highlight_between and other, but never work :

cm = sns.light_palette("blue", as_cmap = True)
df = df.style.background_gradient(cmap=cm, low = -0.2, high = 0.5, text_color_threshold = 0.6 ).set_precision(2)
df.style.highlight_between(left = 3, right = 10, color="green")\
.style.highlight_between(left = -10, right = -3, color="red")
df = df.style.highlight_min(color = 'red', axis=None)
df = df.style.apply(lambda x: ["background-color:lime" if i>3 \
                      elif "background-color:tomato" if i<-3 else "background-color:black" for i in x],
               ) ## Axis=1 : Row and Axis=0: Column

I think my problem is to add multiple style for one df.

An exemple of what I tried :

def highlight(val):
    green = 'background-color: green' if val > 3 else ''
    red = 'background-color: red' if val < -3 else ''
    return green, red

df.style.applymap(highlight)

the red part don't work but just green give me that :

screenshot_result


Solution

  • import pandas as pd
    import numpy as np
    
    np.random.seed(0)
    df = pd.DataFrame((np.random.rand(5,10) - 0.5) * 20)
    
    df.style.applymap(lambda x: f"background-color: {'lime' if x > 3 else 'tomato' if x < -3 else 'white'}")
    

    enter image description here

    You can also chain styles like that to produce the same result:

    df.style.applymap(lambda x: f"background-color: {'lime' if x > 3 else ''}")\
            .applymap(lambda x: f"background-color: {'tomato' if x < -3 else ''}")