4

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)

datapug
  • 2,261
  • 1
  • 17
  • 33

2 Answers2

4

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.

nikhilweee
  • 3,953
  • 1
  • 18
  • 13
0

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

Nick ODell
  • 15,465
  • 3
  • 32
  • 66
The Mask
  • 390
  • 3
  • 17
  • Do you have any reference link on what is the proper way to incorporate JavaScript for the sorting? – datapug Dec 16 '20 at 18:46
  • pandas.Dataframe.to_html() will convert the Dataframe into element.After that you can try this https://stackoverflow.com/questions/14267781/sorting-html-table-with-javascript SO answer for sorting purpose.
    – The Mask Dec 16 '20 at 19:00
  • If this worked out for you then please mark it as accepted so that others can take advantage of it. – The Mask Dec 17 '20 at 07:20
  • It didn't work yet: I am new to JS and when I tried the code in the post mentioned (and wrapped the script into `` and `window.onload=function()` ) and it still not working. I'll accept the answer when I figure out why is not working or when a working snippet is provided in this post. – datapug Dec 17 '20 at 15:50