Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. Any help would be greatly appreciated.

Thanks!

like image 375
OptionAndrew Avatar asked May 07 '18 18:05

OptionAndrew


1 Answers

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

like image 114
jezrael Avatar answered Oct 12 '22 10:10

jezrael