I am trying to change color of text in the rows of a table created using df.to_html()
Condition is if text "Critical" exists in a column then whole row’s text should be Red colored.
Sample Table –
Severity Name Description Type
ABC lorem ipsum Car
Critical DEF something Bike
GHI foo data Car
High XYZ numbers Car
The rows with Critical (i.e., Name: ABC, DEF, GHI) should get text colored red.
Below is the code I tried initially
html_table = df.to_html()
html_table = html_table.replace('<td>{}</td>'.format(), '<td style="color:red;">{}</td>'.format()
Any help on this would be appreciated.
2
Answers
You can define a function that goes through each row of the dataframe and checks the content of the
Severity
column. Once this is done, it colors all cells of that row Red.giving you this output:
You can use the Pandas styler to set up your conditional formatting. Something like this:
This generates the CSS section of your HTML, and an HTML table with IDs matching the CSS selectors (not as pretty as being able to add a specific class to the entire
tr
element, but it gets the job done)For more information, see Pandas’s official docs about
style.apply