datapug
datapug

Reputation: 2431

Export a pandas dataframe to a sortable table in HTML

Is there a way to export a pandas dataframe into an HTML file and incorporate some additional code that makes the output sortable by column?

I have been using Dash DataTable to give the user the option to sort the results, but I was wondering if there is another way in which a server running is not needed and the user can just load the HTML page and sort the results.

So far I have been able to have semi interactive plots based on this SO post, but I would like to add also sortable tables in the HTML and after searching online I am not clear what is the best way to do it (still a newbie with HTML)

Upvotes: 6

Views: 6051

Answers (2)

James Morrison
James Morrison

Reputation: 59

I used panel for this purpose (version 0.14.2). It creates sortable HTML tables by default.

import panel as pn
# df denotes your existing pandas DataFrame
df = pn.widgets.Tabulator(df)
# df.datetime = df.datetime.astype(str)
df.save("df.html")

If you have columns which are datetimes or timedeltas it may be best to cast them to string first for more sensible representation.

If you wish for a timedelta to be sortable it is best to convert it to a sensible integer.

Upvotes: 5

The Mask
The Mask

Reputation: 579

For sorting you have to use JavaScript and for the exporting part use method pandas.DataFrame.to_html().

Upvotes: 1

Related Questions