Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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],
        '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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading