Kelvin Lo
Kelvin Lo

Reputation: 199

Pandas highlight specific number with different color in dataframe

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!

Upvotes: 2

Views: 805

Answers (3)

Henry Ecker
Henry Ecker

Reputation: 35646

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

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71580

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)

Upvotes: 1

Sameet
Sameet

Reputation: 61

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)

Upvotes: 0

Related Questions