2

I'm trying to highlight specific number with different color in my dataframe below:

import pandas as pd
df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list("ABC"))

I can highlight a specific number by one color, for example:

def HIGHLIGHT_COLOR(x):
criteria = x == 4
return ['background-color: green' if i else '' for i in criteria]

df.style.apply(HIGHLIGHT_COLOR)

What I need is to highlight every individual number, here's my code but it doesn't work:

def HIGHLIGHT_COLOR(x):
    if x == 4:
        color = green
    elif x == 2:
        color = yellow
    elif x == 3:
        color = grey
    elif x == 7: 
        color = purple
    elif x == 10:
        color = black
    return f'color: {color}'

df.style.apply(HIGHLIGHT_COLOR)

Can anyone assist this? Thank you!

3 Answers 3

2

An option with Series.map and Series.fillna:

def HIGHLIGHT_COLOR(x):
    return ('background-color: ' + x.map({
        4: 'green',
        2: 'yellow',
        3: 'grey',
        7: 'purple',
        10: 'black'
    })).fillna('')


df.style.apply(HIGHLIGHT_COLOR)

styled

Sign up to request clarification or add additional context in comments.

Comments

1

Do you mean by:

def HIGHLIGHT_COLOR(inp):
    colors = []
    for x in inp:
        if x == 4:
            colors.append('green')
        elif x == 2:
            colors.append('yellow')
        elif x == 3:
            colors.append('grey')
        elif x == 7: 
            colors.append('purple')
        elif x == 10:
            colors.append('black')
    return [f'background-color: {color}' for color in colors]

df.style.apply(HIGHLIGHT_COLOR)

3 Comments

Thank you. That was what I meant. However, your code doesn't work either. Anything missed?
Due to an error code, I had to add colors=[] in front of for loop. However, it still is not working properly. Thank you though!
It shows "Function <function HIGHLIGHT_COLOR at 0x00000226ABC86F70> returned the wrong shape. Result has shape: (3,) Expected shape: (3, 3)"
0

After adjusting your function here is my solution:

def HIGHLIGHT_COLOR(x):
    def colour_switch(number):
        if number == 4:
            color = "green"
        elif number == 2:
            color = "yellow"
        elif number == 3:
            color = "grey"
        elif number == 7: 
            color = "purple"
        elif number == 10:
            color = "black"
        else:
            # default
            color = "white"
            
        return color

    return [f'background-color: {colour_switch(number)}' for number in x]

df.style.apply(HIGHLIGHT_COLOR)

1 Comment

Thanks a million! It is working perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.