highlight two rows on condition in one row pandas

I want to highlight condition 1: every row in B which contains "a" and condition 2: if a row in B is highlighted the corresponding row in ID should be highlighted as well

import pandas as pd
import numpy as np
data = {'ID':[1,2,3,4,5,6,7,8,9,10],
        'C': [5,7,8,9,12,3,60,55,20,14]
df = pd.DataFrame(data=data)
    .apply(lambda x: np.where(x == "a", 'background-color : red', ''),axis=1, 

to highlight condition 1 I used the above which works but I don’t know how to implement the second condition.

>Solution :

One option using axis=None to work on the whole DataFrame at once:

def color(df, cols=None):
    if cols is None:
        cols = df.columns
    mask = pd.DataFrame(columns=df.columns, index=df.index)
    mask[cols] = np.tile(np.where(df['B'].eq('a'),
                                'background-color: yellow', ''
                               )[:,None], (1, len(cols)))
    return mask

df.style.apply(color, cols=['ID', 'B'], axis=None)


enter image description here

Leave a Reply