Export a Pandas DataFrame to HTML table


If you ever tried to write a big table in HTML from scratch, you know how much it can be tedious. Fortunately, there are ways to convert data from a Pandas DataFrame to a HTML table with a simple call.

Making tables in HTML from Pandas DataFrames

Pandas Dataframe to HTML table
From Pandas to HTML seamlessly!

HTML is the standard language of the web. Virtually all websites you see are rendered in HTML. Together with CSS and JavaScript, it builds the basic infrastructure of the web as we know it.

If you spent time more than once creating a table from scratch in HTML, you know it may be a terribly tedious process. And probably you dread going back and change that table, in case it needs to be updated.

Fortunately, other smart people had the same problem before and decided to do something about it. Amongst the large number of formats you can export data to in Pandas, you can also find HTML.

Creating your table

Let’s imagine you are handling your data in a Jupyter Notebook, and you want to export your results for inserting into your HTML page. Most probably, the object holding that data in a tabular format will be a Pandas DataFrame.

Then it’s your lucky day! All you need to do is to call one of the fantastic DataFrame methods:

import pandas as pd
df = pd.DataFrame({
    "X": [10, 5, 7], 
    "Y": [21,15,9], 
    "p": [0.631, 0.557,0.364]

The above command will return you a string with the Pandas DataFrame formatted as HTML Table and ready to be inserted in your HTML webpage. Specifically:

<table border="1" class="dataframe">
    <tr style="text-align: right;">

The code above will render as follow in your webpage:

This is how the HTML table will look like

There is a long set of parameters available to you in order to fine-tune the Latex table. Here I report some of the most useful:

  • columns: the list of columns to export (by default, all of them)
  • col_space: the minimum width of each column
  • index: whether to write row names (by default True)
  • notebook: whether the table is for inserting in a Jupyter Notebook (by default False)
  • classes: string or list or tuple with CSS classes to be added in the generated HTML

Related links

  • Pandas DataFrame.to_html() documentation link

Do you like our content? Check more of our posts in our blog!