Python Pandas - Exporting DataFrames to HTML



Python's Pandas library provides an easy way to convert a DataFrame to an HTML file using the to_html() method. This is particularly useful when you need to render a DataFrame as an HTML table and display data in a web-based application or save it in an HTML format for further usage.

In this tutorial, we will learn about the different use cases and options available to customize the HTML output while saving the Pandas DataFrame to HTML format.

Introduction to pandas to_html() Method

The to_html() method in Pandas is used to convert a DataFrame into an HTML table. It is particularly useful for displaying DataFrames in web applications, like Jupyter notebooks.

Following is the syntax of this method −

DataFrame.to_html(buf=None, *, columns=None, header=True, index=True, na_rep='NaN', justify=None, border=None, ...)

Below are the commonly used parameters of this method −

  • buf: If a string or file path is given, the output is written to a file or buffer. Otherwise, it returns the HTML as a string.

  • columns: Select specific columns to include in the output HTML table.

  • header and index: Specifies whether to display of column headers and index labels in the HTML.

  • na_rep: A string specifies how missing values (NaN) are represented in the HTML.

  • border: Adds a border to the table.

  • justify: Determines how column labels are aligned.

Exporting Pandas DataFrame to HTML Table

The DataFrame.to_html() method provides a quick way to convert a Pandas DataFrame into an HTML table. By default, all columns and rows of the DataFrame are included in the HTML output. This method helps generate HTML tables for data visualization and reporting.

Example

Here is the basic example of using the to_html() method for converting a Pandas DataFrame into a simple HTML table. Let's create a DataFrame with random values and render it as HTML.

Open Compiler
import pandas as pd import numpy as np # Create DataFame df = pd.DataFrame({'name': ['Ravi', 'Priya', 'Kiran'], 'salary': [50000, 60000, 65000]}) # Write the DataFrame to an HTML Table html = df.to_html() # Display the HTML output print(html)

When we run the above program, it produces the following result:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
      <th>salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Ravi</td>
      <td>50000</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Priya</td>
      <td>60000</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Kiran</td>
      <td>65000</td>
    </tr>
  </tbody>
</table>

Convert specific Columns of DatarFrame to HTML

Sometimes, you may want to include only a subset of DataFrame columns in the HTML output. The columns parameter allows you to specify which columns to include in the HTML table.

Example

This example demonstrates saving specific columns of a DataFrame to HTML table using the columns argument of the DataFrame.to_html() method. In this example, only column 'name' will appear in the generated HTML table.

Open Compiler
import pandas as pd import numpy as np # Create DataFame df = pd.DataFrame({'name': ['Ravi', 'Priya', 'Kiran'], 'salary': [50000, 60000, 65000]}) # Write the DataFrame to an HTML Table html = df.to_html(columns=['name']) # Display the HTML output print(html)

Following is the output of the above code −

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Ravi</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Priya</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Kiran</td>
    </tr>
  </tbody>
</table>

Adding Styles to HTML Table While Exporting

The classes parameter of the DataFrame.to_html() method allows you to assign custom CSS classes to the HTML table. This is useful when you want to style your table using predefined or custom CSS styles.

Example

The following example shows how to apply custom CSS styles to a Pandas DataFrame's HTML output using the classes parameter of the DataFrame.to_html() method. In this example, we add the CSS classes "custom_table", and "highlighted" to the output HTML table.

Open Compiler
import pandas as pd import numpy as np # Create DataFame df = pd.DataFrame({'name': ['Ravi', 'Priya', 'Kiran'], 'salary': [50000, 60000, 65000]}) # Add custom CSS classes to the HTML table html_with_classes = df.to_html(classes=["custom_table", "highlighted"]) # Display the HTML output print(html_with_classes)

Following is the output of the above code −

<table border="1" class="dataframe custom_table highlighted">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>name</th>
      <th>salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Ravi</td>
      <td>50000</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Priya</td>
      <td>60000</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Kiran</td>
      <td>65000</td>
    </tr>
  </tbody>
</table>

Handling Special Characters in HTML Export

By default, special characters like <, >, and & are escaped to ensure valid HTML output. If you want to include raw HTML, you can disable escaping with the escape parameter.

Example

This example shows how to handle the special characters while creating an HTML table from a Pandas DataFrame.

import pandas as pd import numpy as np # Create a DataFrame with special characters special_char_df = pd.DataFrame({"Col1": ["<", ">", "&"], "Col2": [1, 2, 3]}) # Default behavior (escaped) escaped_html = special_char_df.to_html() print("Escaped:\n", escaped_html) # Disable escaping non_escaped_html = special_char_df.to_html(escape=False) print("\nNot Escaped:\n", non_escaped_html)

Output

On executing the above code we will get the following output −

Escaped:
 <table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Col1</th>
      <th>Col2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td><</td>
      <td>1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>></td>
      <td>2</td>
    </tr>
    <tr>
      <th>2</th>
      <td>&</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

Not Escaped:
 <table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Col1</th>
      <th>Col2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td><</td>
      <td>1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>></td>
      <td>2</td>
    </tr>
    <tr>
      <th>2</th>
      <td>&</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

Rendering Hyperlinks in DataFrame HTML Export

The render_links parameter enables hyperlinks for cells containing URLs. This is particularly useful for creating interactive tables where users can navigate to relevant resources.

Example

The following example demonstrates adding the hyperlinks while saving Pandas DataFrame to HTML table.

Open Compiler
import pandas as pd import numpy as np url_df = pd.DataFrame({"Name": ["Tutorialspoint", "Python Pandas Tutorial"], "URL": ["https://www.tutorialspoint.com/index.htm", "https://www.tutorialspoint.com/python_pandas/index.htm"] }) # Render URLs as clickable links html_with_links = url_df.to_html(render_links=True) # Display the HTML output print(html_with_links)

The result of the above code is as follows:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Name</th>
      <th>URL</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Tutorialspoint</td>
      <td><a href="https://www.tutorialspoint.com/index.htm" target="_blank">https://www.tutorialspoint.com/index.htm</a></td>
    </tr>
    <tr>
      <th>1</th>
      <td>Python Pandas Tutorial</td>
      <td><a href="https://www.tutorialspoint.com/python_pandas/index.htm" target="_blank">https://www.tutorialspoint.com/python_pandas/index.htm</a></td>
    </tr>
  </tbody>
</table>
Advertisements