6

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)

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

AttributeError: module 'panel.widgets' has no attribute 'Tabulator'
1

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

5 Comments

Do you have any reference link on what is the proper way to incorporate JavaScript for the sorting?
pandas.Dataframe.to_html() will convert the Dataframe into <table> element.After that you can try this stackoverflow.com/questions/14267781/… SO answer for sorting purpose.
If this worked out for you then please mark it as accepted so that others can take advantage of it.
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 <script> </script>` 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 Hi datapug, thank you for asking the questions. I literally face the same issue to you right now. I use pandas.to_html to display my df in html, and trying to find someway to make the columns in the table can be sorted. May I ask if you finally find a result for this? Thank you in advance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.