首页 > 解决方案 > Python pandas - 根据2列的值对行进行样式化/突出显示

问题描述

如果两列中的任何一列(row2/row3 或两者)中有空数据,我试图突出显示该行,以便我可以更容易地看到它。

例如:

col1 col2 col3
a    23    16
b          12
c    12
d

返回结果应该是以黄色突出显示的 b、c、d 行。知道如何实现这一目标吗?谢谢!

标签: pythonpandas

解决方案


使用自定义函数:

def highlight(x):
    c1 = 'background-color: yellow'

    # condition
    m = x.isna().any(axis=1)
    #if need specify columns for check
    m = x[['col2','col3']].isna().any(axis=1)
    #print (m)
    #empty DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    #set new columns by condition
    return df1.mask(m, c1)


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

推荐阅读