Naib
Naib

Reputation: 1029

Apply different conditional formatting to different rows

I typically use pandas to produce nice looking tabulated output in a workbook

How to apply different conditional formatting per row to highlight the cells that fail. Ie for the R1 row, values > 3, R2 row values <5 etc...

or say... for each column, which R2 < R1

R1 = [1,10,3]
R2 = [4,5,6]
E_Rfsw = [7,8,9]

data = [R1, R2,E_Rfsw]
df = pd.DataFrame(data, 
                columns=[V for V in design.Vout],
                index=['FB R1 (kΩ)', 'FB R2 (kΩ)','Fsw resistor (kΩ)'],
                )
display(df.round(4)) 

Upvotes: 2

Views: 418

Answers (1)

jezrael
jezrael

Reputation: 862681

I believe you need custom function with Styler.apply:

def highlight_row(x):
    c1 = 'background-color: red'

    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    #filter index by R1, R2
    m1 = x.index.str.contains('R1')
    m2 = x.index.str.contains('R2')
    #compare filtered rows by conditions and add Falses for all rows
    mask = (x[m1] > 3).append((x[m2] > 5)).reindex(x.index, fill_value=False)
    #set values by mask
    df1 = df1.mask(mask, c1)
    return df1
df.style.apply(highlight_row, axis=None)

Sample data - only removed columns parameter, because design.Vout is not specified:

pic

Upvotes: 3

Related Questions