I couldn’t find a way to do it for a cell so I did it for the row. Here is how you can do it. You will create a function and call that function in the style property for the df.
def highlight_rows(x):
Columns_Num = 3
if x.rating == 2:
return['background-color: lightyellow']*Columns_Num
if x.rating == 3:
return['background-color: lightblue']*Columns_Num
if x.rating >= 4 :
return['background-color: lightgreen']*Columns_Num
Highlighting (and styling in general) is performed using Pandas’ styler. You define a function that returns the CSS to apply and use either applymap to apply it to individual cells, or apply to apply it to rows, columns or the entire table.
From the docs:
Pass your style functions into one of the following methods:
Styler.applymap: elementwise
Styler.apply: column-/row-/table-wise
You can use the subset parameter to apply the style to only specific rows or columns. This is explained in Finer Control: Slicing :
Both Styler.apply , and Styler.applymap accept a subset keyword. This allows you to apply styles to specific rows or columns, without having to code that logic into your style function.
Any extra named properties are passed to your function as parameters. I added threshold so I could experiment a bit.
There are shortcut methods that can apply built-in styles directly. For example, you can use background_gradient to apply a gradient to the ratings column with :