Skip to content

Effortlessly Convert DataFrame to HTML Table in Python


How to Convert DataFrame to HTML Table in Python


In Python, pandas is a widely used library for data manipulation and analysis. It provides a powerful data structure called DataFrame, which is essentially a two-dimensional table. DataFrames can be converted to HTML tables, making it easier to visualize and present data on the web. In this tutorial, we will learn how to convert a DataFrame to an HTML table in Python.

Preparing the Environment

Before we proceed, we need to make sure that we have the required libraries installed. Open your Python IDE or Jupyter Notebook and execute the following command to install pandas:

!pip install pandas

Step 1: Importing the Required Libraries

To begin, let’s import the necessary libraries: pandas and IPython. IPython is an interactive shell that provides enhanced features for working with Python.

import pandas as pd
from IPython.display import display, HTML

Step 2: Creating a DataFrame

Let’s create a simple DataFrame to work with. In this example, we will use a dictionary to define the data and then convert it to a DataFrame.

data = {'Name': ['John', 'Emily', 'Michael', 'Jessica'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'London', 'Paris', 'Tokyo']}
df = pd.DataFrame(data)

Step 3: Converting DataFrame to HTML Table

Now that we have our DataFrame prepared, let’s convert it to an HTML table using the to_html() method provided by pandas.

html_table = df.to_html()

Step 4: Displaying the HTML Table

To display the HTML table, we will make use of the IPython library. By using the display() function, we can render the HTML content in the Jupyter Notebook.


Step 5: Saving the HTML Table to a File

If you want to save the HTML table as a file, you can use the to_html() method again but this time provide the desired file path.



In this tutorial, we have learned how to convert a DataFrame to an HTML table in Python. We started by importing the necessary libraries, followed by creating a DataFrame using sample data. Then, we used the to_html() method to convert the DataFrame into an HTML table. Finally, we displayed the HTML table using the IPython library and learned how to save it as a file.

Using the to_html() method, you can further modify the table by specifying various parameters like table styles, column names, and index visibility. This makes it easier to customize the appearance of the HTML table according to your requirements.