Conditionally format Python pandas cell

From the style docs:

You can apply conditional formatting, the visual styling of a
DataFrame depending on the data within, by using the DataFrame.style
property.

import pandas as pd
df = pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background: red" if v > x.iloc[0] else "" for v in x], axis = 1)

enter image description here


Edit: to format specific cells, you can add condition checkers to check the name of element with Series.iteritems() or check the index with enumerate(), e.g. if you want to format starting from column 3, you can use enumerate and check the index:

df = pd.DataFrame([[2,3,-3], [3,2,7], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background-color: #ff33aa" 
                          if (i >= 2 and (v > x.iloc[0] + x.iloc[1] 
                                          or v < x.iloc[0] - x.iloc[1])) 
                          else "" for i, v in enumerate(x)], axis = 1)

enter image description here

Leave a Comment