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 :
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.