pythonpandasstylingconditional-formatting

Conditional Styling in Pandas using other columns


I've searched and can't seem to find an answer on this anywhere, so hopefully it's possible. I have a dataframe, for simplicity I'll include an abbreviated version below. What I'd like to do is apply a custom formula for styling, or style one particular column based on the values in another column.

enter image description here

Minimal input data:

df = pd.DataFrame({'Current': {0: 13.0, 1: 13.5, 2: 13.75, 3: 14.03, 4: 14.23},
                   'Diff': {0: 0.9, 1: 1.0, 2: 0.95, 3: 0.83, 4: 0.93},
                   'Historic Standard Dev': {0: 1.0, 1: 0.9, 2: 0.93, 3: 0.9, 4: 0.9}})

Using this as an example, I'd like to highlight the Current column's cells where the Diff > Historic Standard Dev in that row.

I've explored the style.apply approaches, but can't seem to find one that works.


Solution

  • You can create DataFrame of styles by Styler.apply:

    def select_col(x):
        c1 = 'background-color: red'
        c2 = '' 
        #compare columns
        mask = x['Diff'] > x['HistoricStandardDev']
        #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.loc[mask, 'Current'] = c1
        return df1
    
    df.style.apply(select_col, axis=None)
    

    pic