How to use Pandas stylers for coloring an entire row based on a given column?

This solution allows for you to pass a column label or a list of column labels to highlight the entire row if that value in the column(s) exceeds the threshold.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
df.iloc[0, 2] = np.nan

def highlight_greaterthan(s, threshold, column):
    is_max = pd.Series(data=False, index=s.index)
    is_max[column] = s.loc[column] >= threshold
    return ['background-color: yellow' if is_max.any() else '' for v in is_max], threshold=1.0, column=['C', 'B'], axis=1)


enter image description here

Or for one column, threshold=1.0, column='E', axis=1)

enter image description here

Leave a Comment