Is there a quick way to turn a pandas DataFrame into a pretty HTML table?

Viewed 23722

Problem: the output of df.to_html() is a plain html table, which isn't much to look at:

ugly table

Meanwhile, the visual representation of dataframes in the Jupyter Notebook is much nicer, but if there's an easy way to replicate it, I haven't found it.

pretty table

I know it should be possible to generate a more aesthetically-pleasing table by fiddling around with df.style, but before I go off learning CSS, has anyone already written a function to do this?

4 Answers

After some research I found the prettiest and easiest solution to be https://pypi.org/project/pretty-html-table/

import pandas as pd
from pretty_html_table import build_table
df = pd.DataFrame(np.arange(9).reshape(3, 3), list('ABC'), list('XYZ'))
html_table_blue_light = build_table(df, 'blue_light')
print(html_table_blue_light)
with open('styled_table.html', 'w') as f:
    f.write(html_table_blue_light)

You could also add the following Raw NBConvert cell at the top of your notebook:

<link rel="stylesheet" href="https://cdn.jupyter.org/notebook/5.1.0/style/style.min.css">

NBConvert seems to fail adding these styles into the exported HTML. The line above will add them explicitly.

Source

<link rel="stylesheet" href="https://cdn.jupyter.org/notebook/5.1.0/style/style.min.css">

you need to add class="rendered_html" to <body> otherwise it won't work.

Related