Pandas 在数据框中用不同颜色突出显示特定数字

Pandas highlight specific number with different color in dataframe

我试图在下面的数据框中用不同颜色突出显示特定数字:

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

我可以用一种颜色突出显示特定数字,例如:

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

df.style.apply(HIGHLIGHT_COLOR)

我需要突出显示每个单独的数字,这是我的代码,但它不起作用:

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)

有人可以帮忙吗?谢谢!

您的意思是:

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)

调整你的功能后,这是我的解决方案:

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)

带有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)