1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.