将条件格式应用于熊猫数据框中的整行

时间:2021-03-21 06:57:40

标签: python pandas dataframe styling conditional-formatting

我想将条件格式应用于数据框中的整行,其中有许多名为 Total 的行

def highlight_total(s):
    is_total=s=='Total'
    return['background-color: yellow' if v else '' for v in is_total]

df.style.apply(highlight_total)

但它仅突出显示 Total 单元格而不是整行

1 个答案:

答案 0 :(得分:0)

假设您的 DataFrame 包含:

   Title   v1   v2   v3
1  Xxxx1   20   30   40
2  Yyyy1   80  170  260
3  Total  100  200  300
4  Xxxx2   70  120  210
5  Yyyy2  120  190  240
6  Total  190  310  450

然后,用 'Total'Title 突出显示整行:

  1. 定义如下函数:

    def rowStyle(row):
        if row.Title == 'Total':
            return ['background-color: yellow'] * len(row)
        return [''] * len(row)
    
  2. 运行:df.style.apply(rowStyle, axis=1)(我假设您使用 Jupyter Notebook).

对于我得到的上述数据:

enter image description here

如果您还想突出显示索引列,请运行:

df.reset_index().rename(columns={'index': ''}).style\
    .apply(rowStyle, axis=1).hide_index()
相关问题