How to Render a Panda Data Frame as HTML

Sometimes it might be useful to convert a Panda Dataframe to HTML. For instance, you might want to render a panda data frame inside a web page, outside Jupyter Notebook. You can do this by calling the df.to_html() function. Where df is the Panda data frame that you would like to render.

Let’s first create a panda data frame. A simple one….

import pandas as pd

df = pd.DataFrame.from_records([["one","two","three"]], columns= ["First", "Second", "Third"])
df

Now to convert it to HTML, we simply can do:
df.to_html()

And this is what we get:

<table border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th></th>\n      <th>First</th>\n      <th>Second</th>\n      <th>Third</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>one</td>\n      <td>two</td>\n      <td>three</td>\n    </tr>\n  </tbody>\n</table>

Let’s render the HTML in our Jupyter notebook using IPython.core.display:

from IPython.core.display import HTML
HTML(df.to_html())

And there you have it. We have an HTML Table.

But let’s suppose that this table contains an URL in a fourth column. Something like this:

import pandas as pd

df = pd.DataFrame.from_records([["one","two","three", "https://upload.wikimedia.org/wikipedia/commons/9/94/The_Nativity_MET_DP207823.jpg"]], columns= ["First", "Second", "Third", "Image"])
df

After running this in a Jupyter notebook we will get something like this:

And if we convert the Panda data frame to HTML:

from IPython.core.display import HTML
HTML(df.to_html())

Not great!
Would it not be nice if we could just display the image instead of the URL? This is something that if we are in the context of analysing data, is incredibly useful.

Using a column formatter with pandas.to_html()

We are in luck, the Pandas library allows us to customize the HTML output for each column. In this way, we can pass a separate function, one per column in the formatters parameter:

def url_to_image_html(imageUrl):
  return f"<img src='{imageUrl}' width='120'/>"

from IPython.core.display import HTML
HTML(df.to_html(escape=False, formatters=dict(Image=url_to_image_html)))

And we get:

It will come handy right?