Home > Software engineering >  Color only certain rows and columns of a Pandas DataFrame
Color only certain rows and columns of a Pandas DataFrame

Time:03-24

I have a data frame with looks something like this

df = pd.DataFrame({'name':['a','b','c'],
               'standard':['st1','st2','st3'],
               'section':['s1','s2','s3'],
              'subject1': [98,92,99.5],
              'subject2': [99,99,95.8],
              'subject3': [90,91,100]})

Note: The columns 'subject1','subject2' and 'subject3' are generated dynamically and might NOT be the same every time.

I am trying to color only the columns 'subject1','subject2' and 'subject3' in the Data Frame in red when

  • The cells have a value of less than 98.5 and
  • The value of the column 'standard' is 'st2'.

To be precise, in the above mentioned Data Frame, I only want to color the second row (standard = 'st2') and only the subject columns ('subject1','subject2' and 'subject3') when the cell value is less than 98.5

What would be the ideal way to do this?

Thanks in advance...

CodePudding user response:

You can create DataFrame of styles by Styler.apply and set values by conditions:

def hightlight(x):
    c1 = 'background-color: red'
    c2 = '' 
    #compare columns
    cols = ['subject1','subject2','subject3']
    mask = x[cols] < 98.5
    mask1 = x['standard'].eq('st2').to_numpy()[:, None]
    #DataFrame with same index and columns names as original filled empty strings
    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    #modify values of df1 column by boolean mask
    df1[cols] = df1[cols].mask(mask & mask1, c1)
    return df1

df.style.apply(hightlight, axis=None)

CodePudding user response:

Try:

def highlight_low(s, props=''):
    return np.where(s<98.5, props, '')

>>> df.style.apply(highlight_low, 
                   props="background-color:red", 
                   subset=pd.IndexSlice[pd.IndexSlice[df["standard"].eq("st2")], 
                                        df.filter(like="subject").columns])

Formatted dataframe

  • Related