skip to Main Content

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


  1. 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.

    import pandas as pd
    
    data = {
        'Severity': ['', 'Critical', '', 'High'],
        'Name': ['ABC', 'DEF', 'GHI', 'XYZ'],
        'Description': ['lorem ipsum', 'something', 'foo data', 'numbers'],
        'Type': ['Car', 'Bike', 'Car', 'Car']
    }
    df = pd.DataFrame(data)
    
    def color_critical_rows(df):
        html = df.to_html(index=False)
    
        rows = html.split('</tr>')
        new_rows = []
    
        for row in rows:
            if 'Critical' in row:
                new_row = row.replace('<td>', '<td style="color: red;">')
            else:
                new_row = row
            new_rows.append(new_row)
    
        new_html = '</tr>'.join(new_rows)
    
        return new_html
    
    colored_html_table = color_critical_rows(df)
    print(colored_html_table)
    
    

    giving you this output:

    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th>Severity</th>
          <th>Name</th>
          <th>Description</th>
          <th>Type</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td></td>
          <td>ABC</td>
          <td>lorem ipsum</td>
          <td>Car</td>
        </tr>
        <tr>
          <td style="color: red;">Critical</td>
          <td style="color: red;">DEF</td>
          <td style="color: red;">something</td>
          <td style="color: red;">Bike</td>
        </tr>
        <tr>
          <td></td>
          <td>GHI</td>
          <td>foo data</td>
          <td>Car</td>
        </tr>
        <tr>
          <td>High</td>
          <td>XYZ</td>
          <td>numbers</td>
          <td>Car</td>
        </tr>
      </tbody>
    </table>
    
    Login or Signup to reply.
  2. You can use the Pandas styler to set up your conditional formatting. Something like this:

    import pandas as pd
    
    CRITICAL = 'critical'
    
    # create dataframe
    df = pd.DataFrame(data={
        'severity': ['critical', 'critical', 'critical', 'high'],
        'name': ['ABC', 'DEF', 'GHI', 'XYZ'],
        'description': ['lorem ipsum', 'something', 'foo data', 'numbers'],
        'type': ['car', 'bike', 'car', 'car']
    })
    
    # sets the style for all cells in the row if the severity is critical
    def cond(x):
        if x.severity == CRITICAL: 
             return ['background-color: red'] * len(x)
    
    df_styled = df.style.apply(cond, axis=1)
    print(df_styled.to_html())
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search