I\'m trying to replicate the output that jupyter uses for a pandas dataframe in their notebooks to html/css/js so that it\'s returnable by Flask jsonify
as html
I've made a few changes to your code to get the functionality you want:
thead
for the header and tbody
for the body. We can use this to specify the highlighting behavior as body-onlyIn Jupyter Notebook:
import pandas as pd
import numpy as np
from IPython.display import HTML
def hover(hover_color="#add8e6"):
return dict(selector="tbody tr:hover",
props=[("background-color", "%s" % hover_color)])
styles = [
#table properties
dict(selector=" ",
props=[("margin","0"),
("font-family",'"Helvetica", "Arial", sans-serif'),
("border-collapse", "collapse"),
("border","none"),
("border", "2px solid #ccf")
]),
#header color - optional
dict(selector="thead",
props=[("background-color","#cc8484")
]),
#background shading
dict(selector="tbody tr:nth-child(even)",
props=[("background-color", "#fff")]),
dict(selector="tbody tr:nth-child(odd)",
props=[("background-color", "#eee")]),
#cell spacing
dict(selector="td",
props=[("padding", ".5em")]),
#header cell properties
dict(selector="th",
props=[("font-size", "125%"),
("text-align", "center")]),
#caption placement
dict(selector="caption",
props=[("caption-side", "bottom")]),
#render hover last to override background-color
hover()
]
html = (df.style.set_table_styles(styles)
.set_caption("Hover to highlight."))
html
...but is it still beautiful when we output the HTML file?? Yes. You can do some more CSS styling to get it just right (font-size, font-family, text-decoration, margin/padding, etc) but this gives you a start. See below:
print(html.render())
Hover to highlight.
0
first
second
bar
one
-0.130634
two
1.17685
baz
one
0.500367
two
0.555932
foo
one
-0.744553
two
-1.41269
qux
one
0.726728
two
-0.683555