Pandas 文本样式条件格式(突出显示)

Pandas Style conditional formatting (highlight) on text

我试图根据文本突出显示 pandas 中的单个完整单元格。例如,如果 Recommend 是 'SELL',我想用红色和绿色突出显示 'BUY'。如果有人可以指导我,我将不胜感激。

def color_negative_red(value):
    if value < 0:
        color = 'red'
    elif value > 0:
        color = 'green'
    else:
        color = 'black'
    return 'color: %s' % color

import pandas as pd

data = {'Stock': ['TSLA','GM','GOOG','MMM'],
        'Diff': [-200,-50,150,50],
        'Recommend' : ['SELL','SELL','BUY','BUY']
        }

df = pd.DataFrame(data, columns = ['Stock', 'Diff', 'Recommend'])

df.style.applymap(color_negative_red, subset=['Diff'])

### how to get a conditional highlight based on 'Recommend' ?????

样式可以链接在一起。有很多方法可以解决这个问题,假设只有 'BUY' 和 'SELL' 选项 np.where + apply 是一个不错的选择:

def color_recommend(s):
    return np.where(s.eq('SELL'),
                    'background-color: red',
                    'background-color: green')

(
    df.style.applymap(color_negative_red, subset=['Diff'])
        .apply(color_recommend, subset=['Recommend'])
)

或者以类似于 color_negative_red 的方式:

def color_recommend(value):
    if value == 'SELL':
        color = 'red'
    elif value == 'BUY':
        color = 'green'
    else:
        return
    return f'background-color: {color}'


(
    df.style.applymap(color_negative_red, subset=['Diff'])
        .applymap(color_recommend, subset=['Recommend'])
)

你快到了!

def color_negative_red(value):
    if value < 0:
        color = 'pink'
    elif value > 0:
        color = 'lightgreen'
    else:
        color = 'white'
    return 'background-color: %s' % color

import pandas as pd

data = {'Stock': ['TSLA','GM','GOOG','MMM'],
        'Diff': [-200,-50,150,50],
        'Recommend' : ['SELL','SELL','BUY','BUY']
        }

df = pd.DataFrame(data, columns = ['Stock', 'Diff', 'Recommend'])

df.style.applymap(color_negative_red, subset=['Diff'])

唯一需要改变的是颜色需要变成background-color:return 'background-color: %s' % color

如果您想突出显示整行,请尝试:

def color_negative_red(row):
    print(row)
    value = row.loc["Diff"]
    if value < 0:
        color = 'pink'
    elif value > 0:
        color = 'lightgreen'
    else:
        color = 'black'
    return ['background-color: %s' % color for r in row]

import pandas as pd

data = {'Stock': ['TSLA','GM','GOOG','MMM'],
        'Diff': [-200,-50,150,50],
        'Recommend' : ['SELL','SELL','BUY','BUY']
        }

df = pd.DataFrame(data, columns = ['Stock', 'Diff', 'Recommend'])

df.style.apply(color_negative_red, axis=1)