How to use Python 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

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

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
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]


df.style.apply(highlight_greaterthan, threshold=1.0, column=['C', 'B'], axis=1)

Output:

enter image description here

Or for one column

df.style.apply(highlight_greaterthan, threshold=1.0, column='E', axis=1)

enter image description here


Here is a simpler approach:

  1. Assume you have a 100 x 10 dataframe, df. Also assume you want to highlight all the rows corresponding to a column, say "duration", greater than 5.

  2. You first need to define a function that highlights the cells. The real trick is that you need to return a row, not a single cell. For example,

    def highlight(s):
        if s.duration > 5:
            return ['background-color: yellow']*10
        else:
            return ['background-color: white']*10
    

**Note that the return part should be a list of 10 (corresponding to the number of columns). This is the key part.

  1. Now you can apply this to the dataframe style as:

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

Tags:

Python

Pandas