
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
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.
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.
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.
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.
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>