Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 445
KevinH Avatar asked Jul 31 '17 17:07

KevinH


People also ask

How do I export pandas DataFrame to HTML?

To render a Pandas DataFrame to HTML Table, use pandas. DataFrame. to_html() method. The total DataFrame is converted to <table> html element, while the column names are wrapped under <thead> table head html element.

How do I print a DataFrame neatly?

You can use the print() method to print the dataframe in a table format. You can convert the dataframe to String using the to_string() method and pass it to the print method which will print the dataframe.

Can you use pandas in HTML?

Introduction. The pandas read_html() function is a quick and convenient way to turn an HTML table into a pandas DataFrame. This function can be useful for quickly incorporating tables from various websites without figuring out how to scrape the site's HTML.

Which is faster than pandas?

On joining two datasets task, Polars has done it in 43 seconds. Meanwhile, Pandas did it in 628 seconds. We can see that Polars is almost 15 times faster than Pandas.

Can you pickle DataFrame?

DataFrame - to_pickle() functionThe to_pickle() function is used to pickle (serialize) object to file. File path where the pickled object will be stored. A string representing the compression to use in the output file. By default, infers from the file extension in specified path.


1 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)
like image 83
DaveR Avatar answered Sep 27 '22 23:09

DaveR