How to Write a Styler to HTML-CSS Format?

Write A Styler Object To HTML CSS Format

Styler to HTML is a very interesting and fun task when we have a special method designed for this purpose. I’m talking about the Pandas Library’s method- Styler.to_html.

This method beautifies a table(in this case, a data frame). This beautification is done with the help of another method of the pandas library called the style.Styler.

When this beautified data is passed as input to Styler.to_html, we get an HTML code in the form of a string as an output. This output can further be used to generate any webpage using editors.

In this tutorial, we will take a data frame, style it and obtain an HTML code out of it.

Do read this similar post on how to render a data frame as an HTML table.

Let us first try to understand what are Styler and HTML.

What Is HTML?

HTML stands for HyperText Markup Language. HTML helps us to create websites and webpages and make them look colorful. When an HTML code is executed, it displays a static webpage in a browser. HTML runs on tags. There are different types of tags for paragraphs, headings, and even images.

With HTML, CSS(cascading style sheet), and JavaScript, you can design your websites and do wonders!

We know that the Pandas library is a very useful tool to be able to work with data of any form. This library has multiple methods to work with HTML code too!

Read this post to learn how to read HTML tables using the Pandas library.

Let us see a simple HTML code to display a message in the web browser.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TEST</title>
</head>
<body>
    <h1> TEST DOCUMENT</h1>
    <p>HELLO WORLD!</p>
</body>
</html>

Inside the head element, we have specified the page’s title with the title tag’s help.

Coming to the body, we have given a heading(h1). This header is customizable, which means it can be anything from h0,h1,h2, and so on. Then in the paragraph tags(p), we wrote a simple message- HELLO WORLD! At last, the body and html tags are closed.

When this code is run, it creates a webpage in your browser.

HTML Page
HTML Page

You can customize your page using different colors, fonts, and backgrounds.

Note: I have used Microsoft Visual Studio Code for this example. You can use any editor of your choice. Online HTML editors work just fine too!

Visit this article to learn how to display a data frame as an HTML table.

Styler Class Explained

A simple and plain data frame might be boring to look at. What if we could make this dull-looking data frame more informative and visually appealing?

The style attribute of the Pandas library does just that. We can use this attribute to create a styler object. This method is used to color-code the elements of a data frame or a series, highlight some data, visualize the data frame, and much more.

Let us see an example of how to apply this method to a pandas data frame.

Let us generate a data frame of 50 random values and style it.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(50, size=(4,6)))
print(df)

We have imported the pandas and numpy library in the above code snippet. The random function of the numpy library is used to create a data frame of 24 entries spread across 4 rows and 6 columns.

All the entries are between 1 and 50.

This data frame is called df.

We are printing the above data frame using print().

Plain Data Frame
Plain Data Frame

In this data frame, let us highlight each row’s maximum and minimum values using the styler object.

df.style.highlight_min(color='yellow',axis=1)\
.highlight_max(color='green', axis=1)

In this snippet, we have used the highlight_max and highlight_min properties of the style method to mark the minimum values of the row with yellow and the maximum values with green. The axis=1 applies changes to rows.

This code is customizable. You can use different colors and experiment. If you want to obtain column-wise maximum and minimum values, change the axis component to axis=0.

Styled Data Frame
Styled Data Frame

Exploring the Styler to HTML Method

This method has the following syntax.

Styler.to_html(buf=None, *, table_uuid=None, table_attributes=None, sparse_index=None, sparse_columns=None, bold_headers=False, caption=None, max_rows=None, max_columns=None, encoding=None, doctype_html=False, exclude_styles=False, **kwargs)

Let us see a quick explanation of the arguments.

Argument Description
bufThis argument takes the file path or buffer where you want the output to be written in
If this argument is not provided, the output is a string
table_uuidThis argument is used to specify the id attribute of the table
If specified, it is displayed as the id
Else, the initial Styler attribute is considered as default
Takes a string(str) as input
table_attributesThis field contains all the attributes the user wishes to include inside the <table> tag
If not specified, the Styler’s attributes are considered
Has the default type of a string
sparse_indexThe DOCTYPE html property gives a structured html code
If this field is specified, the output contains a properly structured HTML code
Else, just the <style> and <table> components are included
The default value is None
sparse_columnsSimilar to sparse_index, but does the same for a column
Default is None
bold_headersIf this argument is used, the CSS code will have a property called font-weight:bold; which writes the headings in bold
Default is False
captionIncludes a caption for the table
Default is None
max_rowsThis argument will decide how many rows the Html table is going to have
Default is None
max_columnsSimilar to max_rows
Determines the number of columns to be included in the table
The default is None meaning every row and column is displayed
encodingThe DOCTYPE html property gives a structured HTML code
If this field is specified, the output contains a properly structured html code
Else, just the <style> and <table> components are included
The default value is None
doctype_htmlThe DOCTYPE html property gives a structured HTML code
If this field is specified, the output contains a properly structured HTML code
Else, just the <style> and <table> components are included
The default value is None
exclude_stylesThis argument decides whether to include the <style> component of the table or just the <table> elements
By default, it is set to False
**kwargsContains any additional arguments to be passed to the .html method
Arguments of Styler to Html

Returns: The HTML code as a string if the buf parameter is None.

Let us look at a few examples of this method.

All the examples we are going to see follow the below process.

  • Creation of a data frame
  • Styling the data frame
  • Obtaining HTML code using the method styler.to_html
  • Creating the web page in the browser with the HTML code
As we have seen earlier, the HTML code is returned in the form of a string enclosed between quotes(' '). Please make sure to remove the quotes and the new line characters(\n) in between to  render a proper HTML code without errors.

Writing Styler to HTML from a Data Frame

In this example, let us take a data frame, set certain conditions to style it, and then render an HTML table.

Let us start with a data frame first.

import pandas as pd
df=pd.DataFrame(([1,12],[13,4],[5,26]))
df

The data frame is created with the help of the pandas library’s method pd.DataFrame. The pandas library is imported in the first line. And the data frame is called df.

In the last line, we are printing the data frame.

Data Frame
Data Frame

Now let us see how we can style this data frame.

s=df.style.highlight_max(color='green',axis=1)
s

We have taken an object called s to store the styled data frame obtained from the df.style. In the above code, we are trying to highlight the maximum values of a row in green.

The styled data frame looks as shown below.

Styled Data Frame
Styled Data Frame

Lastly, we will render an HTML table from this data frame.

s.to_html()
Styler to HTML
Styler to HTML

It looks terrifying. Just try to copy the code and paste it into any HTML editor as per the structure.

The HTML code is supposed to look like this.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style type="text/css">
        #T_85669_row0_col1, #T_85669_row1_col0, #T_85669_row2_col1 {
          background-color: green;
        }
        </style>
        <table id="T_85669" class="dataframe">
          <thead>
            <tr>
              <th class="blank level0" > </th>
              <th id="T_85669_level0_col0" class="col_heading level0 col0" >0</th>
              <th id="T_85669_level0_col1" class="col_heading level0 col1" >1</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th id="T_85669_level0_row0" class="row_heading level0 row0" >0</th>
              <td id="T_85669_row0_col0" class="data row0 col0" >1</td>
              <td id="T_85669_row0_col1" class="data row0 col1" >12</td>
            </tr>
            <tr>
              <th id="T_85669_level0_row1" class="row_heading level0 row1" >1</th>
              <td id="T_85669_row1_col0" class="data row1 col0" >13</td>
              <td id="T_85669_row1_col1" class="data row1 col1" >4</td>
            </tr>
            <tr>
              <th id="T_85669_level0_row2" class="row_heading level0 row2" >2</th>
              <td id="T_85669_row2_col0" class="data row2 col0" >5</td>
              <td id="T_85669_row2_col1" class="data row2 col1" >26</td>
            </tr>
          </tbody>
        </table>
</body>
</html>

When this code is run, it creates a static web page in your web browser.

Webpage
Webpage

As you can see, we have successfully created an HTML code that highlights maximum values with green.

Writing a Styler to HTML With Bold Heading

In this example, we will take a data frame of random values, set a threshold value, and highlight the values below and above this value with different colors. We can do this with the help of a user-defined function.

After we have styled the data frame, we will render an HTML table with all the headers written in bold.

The code for creating a data frame with random values is given below.

import pandas as pd
import numpy as np
df=pd.DataFrame(np.random.randint(100,size=(4,6)))
df

In the above code, we have imported the pandas and numpy libraries to work with data frames.

We have created a variable to store the data frame called df. The random function of the numpy library is used to generate random numbers between 1 and 100. All these numbers are stored in four rows and six columns.

The output is given below.

Data Frame
Data Frame

Now let us see how we can style this data frame.

def gre(val):
    color = 'green' if val > 35 else 'red'
    return f'background-color: {color}'

sdf = df.style.applymap(gre)
sdf

So we have created a function called gre with the help of def keyword. This function is used to assign color based on a certain condition. In this code, I have specified that any value greater than 35 should be highlighted in green. A variable called val is used as an argument to the function. All the other numbers should be highlighted in red. The background-color property of CSS is used to assign the appropriate color.

Next, a variable called sdf stores the styled data frame.The applymap attribute of the Styler class is used to map the color with the respective values.

Styled Data Frame
Styled Data Frame

Lastly, we are rendering an HTML table using this styled data frame and specifying that the headings must be bolded.

sdf.to_html(bold_headers=True)
Styler to HTML with bold headers
Styler to HTML with bold headers

The HTML code is supposed to look like this.

<!DOCTYPE html>
<html>
<title></title>

<head>
</head>

<body>
    <h1></h1>
    <style type="text/css">
        #T_4c668 th {
            font-weight: bold;
        }

        #T_4c668_row0_col0,
        #T_4c668_row0_col1,
        #T_4c668_row1_col0,
        #T_4c668_row2_col0,
        #T_4c668_row2_col3,
        #T_4c668_row2_col4,
        #T_4c668_row2_col5,
        #T_4c668_row3_col1,
        #T_4c668_row3_col2,
        #T_4c668_row3_col3 {
            background-color: red;
        }

        #T_4c668_row0_col2,
        #T_4c668_row0_col3,
        #T_4c668_row0_col4,
        #T_4c668_row0_col5,
        #T_4c668_row1_col1,
        #T_4c668_row1_col2,
        #T_4c668_row1_col3,
        #T_4c668_row1_col4,
        #T_4c668_row1_col5,
        #T_4c668_row2_col1,
        #T_4c668_row2_col2,
        #T_4c668_row3_col0,
        #T_4c668_row3_col4,
        #T_4c668_row3_col5 {
            background-color: green;
        }
    </style>
    <table id="T_4c668">
        <thead>
            <tr>
                <th class="blank level0"> </th>
                <th id="T_4c668_level0_col0" class="col_heading level0 col0">0</th>
                <th id="T_4c668_level0_col1" class="col_heading level0 col1">1</th>
                <th id="T_4c668_level0_col2" class="col_heading level0 col2">2</th>
                <th id="T_4c668_level0_col3" class="col_heading level0 col3">3</th>
                <th id="T_4c668_level0_col4" class="col_heading level0 col4">4</th>
                <th id="T_4c668_level0_col5" class="col_heading level0 col5">5</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th id="T_4c668_level0_row0" class="row_heading level0 row0">0</th>
                <td id="T_4c668_row0_col0" class="data row0 col0">11</td>
                <td id="T_4c668_row0_col1" class="data row0 col1">31</td>
                <td id="T_4c668_row0_col2" class="data row0 col2">98</td>
                <td id="T_4c668_row0_col3" class="data row0 col3">63</td>
                <td id="T_4c668_row0_col4" class="data row0 col4">49</td>
                <td id="T_4c668_row0_col5" class="data row0 col5">81</td>
            </tr>
            <tr>
                <th id="T_4c668_level0_row1" class="row_heading level0 row1">1</th>
                <td id="T_4c668_row1_col0" class="data row1 col0">12</td>
                <td id="T_4c668_row1_col1" class="data row1 col1">50</td>
                <td id="T_4c668_row1_col2" class="data row1 col2">59</td>
                <td id="T_4c668_row1_col3" class="data row1 col3">87</td>
                <td id="T_4c668_row1_col4" class="data row1 col4">38</td>
                <td id="T_4c668_row1_col5" class="data row1 col5">66</td>
            </tr>
            <tr>
                <th id="T_4c668_level0_row2" class="row_heading level0 row2">2</th>
                <td id="T_4c668_row2_col0" class="data row2 col0">31</td>
                <td id="T_4c668_row2_col1" class="data row2 col1">37</td>
                <td id="T_4c668_row2_col2" class="data row2 col2">89</td>
                <td id="T_4c668_row2_col3" class="data row2 col3">16</td>
                <td id="T_4c668_row2_col4" class="data row2 col4">8</td>
                <td id="T_4c668_row2_col5" class="data row2 col5">35</td>
            </tr>
            <tr>
                <th id="T_4c668_level0_row3" class="row_heading level0 row3">3</th>
                <td id="T_4c668_row3_col0" class="data row3 col0">64</td>
                <td id="T_4c668_row3_col1" class="data row3 col1">31</td>
                <td id="T_4c668_row3_col2" class="data row3 col2">0</td>
                <td id="T_4c668_row3_col3" class="data row3 col3">33</td>
                <td id="T_4c668_row3_col4" class="data row3 col4">85</td>
                <td id="T_4c668_row3_col5" class="data row3 col5">44</td>
            </tr>
        </tbody>
    </table>
</body>

</html>

When this code is run, it creates an HTML table in the web browser with bold headers.

Web Page
Web Page

Writing Styler to HTML with the Doctype

In this example, we are going to see the creation of a data frame using a dictionary and styling it as a bar plot.

This styled data frame is then used to render an HTML code that has the DOCTYPE structure.

import pandas as pd
dict={'Name':['Akhil','Anand','Bhavya','Chandu','Divya'],
     'Marks':[98,76,80,65,92],
     'Age':[22,21,23,22,25]}
df=pd.DataFrame(dict)
df

The data frame is given below.

Data Frame
Data Frame

Let us style the data frame now. We are going to compute the mean of the Marks using groupby function, create a barplot for this function, and highlight it with red.

s=df.groupby(['Marks'], as_index=False).mean().\
style.bar(color='red')
s

The styled data frame is given below.

Styled Dataframe
Styled Dataframe

Now let us obtain an HTML code using .to_html() method. In this method, we also specify the doctype_html parameter as True, which creates an HTML code in the DOCTYPE HTML5.

s.to_html(doctype_html=True)
Styler to HTML With DOCTYPE
Styler to HTML With DOCTYPE

What is the difference if we use doctype_html and if we don’t?

You had seen the output when we did not use the doctype_html in the method. As discussed in the syntax, this renders an HTML code with the base elements like <style> and <table>. But we get a standard HTML code as the output if we use it.

The HTML code is supposed to look like this.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <style type="text/css">
        #T_ad601_row0_col0 {
            width: 10em;
            background: linear-gradient(90deg, red 66.3%, transparent 66.3%);
        }

        #T_ad601_row0_col1,
        #T_ad601_row4_col1 {
            width: 10em;
            background: linear-gradient(90deg, red 88.0%, transparent 88.0%);
        }

        #T_ad601_row1_col0 {
            width: 10em;
            background: linear-gradient(90deg, red 77.6%, transparent 77.6%);

        }

        #T_ad601_row1_col1 {
            width: 10em;
            background: linear-gradient(90deg, red 84.0%, transparent 84.0%);
        }

        #T_ad601_row2_col0 {
            width: 10em;
            background: linear-gradient(90deg, red 81.6%, transparent 81.6%);
        }

        #T_ad601_row2_col1 {
            width: 10em;
            background: linear-gradient(90deg, red 92.0%, transparent 92.0%);
        }

        #T_ad601_row3_col0 
        {
            width: 10em;
            background: linear-gradient(90deg, red 93.9%, transparent 93.9%);

        }

        #T_ad601_row3_col1,
        #T_ad601_row4_col0 
        {
            width: 10em;
            background: linear-gradient(90deg, red 100.0%, transparent 100.0%);
        }
    </style>
</head>

<body>
    <table id="T_ad601">
        <thead>
            <tr>
                <th class="blank level0"> </th>
                <th id="T_ad601_level0_col0" class="col_heading level0 col0">Marks</th>
                <th id="T_ad601_level0_col1" class="col_heading level0 col1">Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th id="T_ad601_level0_row0" class="row_heading level0 row0">0</th>
                <td id="T_ad601_row0_col0" class="data row0 col0">65</td>
                <td id="T_ad601_row0_col1" class="data row0 col1">22.000000</td>
            </tr>
            <tr>
                <th id="T_ad601_level0_row1" class="row_heading level0 row1">1</th>
                <td id="T_ad601_row1_col0" class="data row1 col0">76</td>
                <td id="T_ad601_row1_col1" class="data row1 col1">21.000000</td>
            </tr>
            <tr>
                <th id="T_ad601_level0_row2" class="row_heading level0 row2">2</th>
                <td id="T_ad601_row2_col0" class="data row2 col0">80</td>
                <td id="T_ad601_row2_col1" class="data row2 col1">23.000000</td>
            </tr>
            <tr>
                <th id="T_ad601_level0_row3" class="row_heading level0 row3">3</th>
                <td id="T_ad601_row3_col0" class="data row3 col0">92</td>
                <td id="T_ad601_row3_col1" class="data row3 col1">25.000000</td>
            </tr>
            <tr>
                <th id="T_ad601_level0_row4" class="row_heading level0 row4">4</th>
                <td id="T_ad601_row4_col0" class="data row4 col0">98</td>
                <td id="T_ad601_row4_col1" class="data row4 col1">22.000000</td>
            </tr>
        </tbody>
    </table>
</body>

</html>

The web page is created in the web browser after executing the above code.

Web Page
Web Page

Summary

To summarize everything, we have learned how to use the Styler class to style the pandas data frames. We have seen an example of a data frame created with random values and styled so that the minimum values of this data frame are marked with yellow while the maximum values are marked with red.

Next, we have understood what HTML is. We have seen a simple HTML code that creates a web page in the web browser that displays a simple message- HELLO WORLD!

Following that, we have learned the syntax of the method- styler.to_html. We have understood the necessity of each argument of this method.

Coming to the examples, firstly, we have styled a simple data frame so that the maximum values of the data frame are highlighted in green.
This styled data frame is then used to render an HTML code, which produces a web page equivalent to the styled data frame.

In the next example, we followed the same process, but we defined a user-defined function to color the values of the data frame based on a certain condition. We have used the bold_headers argument of the method to make the headings bolder.

Lastly, we tried to create a bar plot of the mean values of the data frame and marked it in red. For converting the styled data frame to HTML, we have used the doctype_html to render HTML code as per the structure.

References

To know more about the Styler class, visit the official pandas documentation.

You can find more about the styler to HTML method here.

Also, refer to this Wikipedia page to know about the available HTML editors.