1

I would like to color the dataframe based on the condition below

   LL    UL   col_1   col_2   col_3   col_4 
1   0    10     5       -6      13      46
2   3    12     0        5       8      55
3 NaN   NaN    -9        8       4       5

I want to color col_1 col_2 col_3 and col_4 if the values is lower than column LL or higher than UL in each row.

If lower, color it red. If higher, color it green.

Moreover, if there is no upper limit and no lower limit, do nothing in that row.

Thanks!

The results may look like this enter image description here

Webcy
  • 181
  • 8

1 Answers1

3

Compare all columns by LL and UL columns and return style DataFrame filled by numpy.select:

def highlight(x):
    c1 = 'background-color: red'
    c2 = 'background-color: green'
    c3 = '' 
    m1 = x.lt(x['LL'], axis=0)
    m2 = x.gt(x['UL'], axis=0)
    #if necessary set first 2 columns to False
    m1.iloc[:, :2] = False
    m2.iloc[:, :2] = False

    out = np.select([m1, m2], [c1, c2], default=c3)
    return pd.DataFrame(out, index=x.index, columns=x.columns)

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

df.style.apply(highlight, axis=None).to_excel('file.xlsx', index=False)

pic

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252