基于两个不同条件的Highlight pandas数据框列

问题描述 投票:1回答:2

我具有以下数据框comp

    time        first_max   name             second_max name.1      Perceived OoM.1 Perceived OoM.2
0   0.000000    18          shoulder_center  9          right_hip   shoulder_center shoulder_center
1   0.010000    18          shoulder_center  9          right_hip   shoulder_center shoulder_center
2   0.020000    18          right_hip        9          right_hip   shoulder_center right_hip
3   0.030000    18          shoulder_center  9          right_hip   shoulder_center right_hip

而且我有此功能根据name == Perceived OoM.1是否突出显示整个行:

def highlight_col(x):
    df = x.copy()
    mask = df['name'] == df['Perceived OoM.1']
    df.loc[mask, :] = 'background-color: yellow'
    df.loc[~mask,:] = 'background-color: ""'
    return df

comp.style.apply(highlight_col, axis=None)

但是,我想找出一种方法来为整行着色name == Perceived OoM.2。基本上,如果name == Perceived OoM.1,我希望该行为黄色;如果name == Perceived OoM.2,我希望该行为蓝色。

但是我似乎无法将此条件应用到我的功能中。

有帮助吗?

python pandas colors apply
2个回答
2
投票

创建另一个掩码并以相同的方式传递,对于默认的空值也使用DataFrame构造函数:

def highlight_col(x):
    df = pd.DataFrame('', index=x.index, columns=x.columns)
    mask1 = x['name'] == x['Perceived OoM.1']
    mask2 = x['name'] == x['Perceived OoM.2']
    df.loc[mask1, :] = 'background-color: yellow'
    df.loc[mask2, :] = 'background-color: blue'
    return df

1
投票

另一种方法是定义一个函数,以便可以在行上应用:

def highlight(x):
    color = 'background-color:yellow' if  x['name']==x['Perceived OoM.1']\
            else 'background-color: green' if x['name']==x['Perceived OoM.2']\
            else ''
    return [color]*len(x)

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

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.