highlight two rows on condition in one row pandas

Question:

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],
        'B':["a","b","c","a","e","f","a","h","c","a"],
        'C': [5,7,8,9,12,3,60,55,20,14]
       }
df = pd.DataFrame(data=data)
(df
    .style
    .apply(lambda x: np.where(x == "a", 'background-color : red', ''),axis=1, 
     subset=["B"])
)

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

Asked By: Hansson

||

Answers:

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)

output:

enter image description here

Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.