Dataframe-To-Styled-Html
May 7, 2022 - ⧖ 3 minI wrote up a little on exporting DataFrames to markdown and html here
But I've been playing with a web app for with lists and while I'm toying around I learned you can actually give your tables some style with some simple css classes!
To HTML
Reminder that if you have a dataframe, df
, you can df.to_html()
to get an HTML table of your dataframe.
Well you can pass some classes
to make it look super nice!
Classes and CSS
I don't know anything really about CSS so I won't pretend otherwise, but as I was learning about bootstrap that's where I stumbled upon this...
There are several classes you can pass but I found really good luck with table-bordered
and table-dark
for my use case
df.to_html(classes=["table table-bordered table-dark"])
Unnamed: 0 | mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb |
---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 |
Mazda RX4 Wag | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
Datsun 710 | 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 |
Hornet 4 Drive | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
Hornet Sportabout | 18.7 | 8 | 360.0 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 |
You try it!
Crack open ipython and make a dataframe, then df.to_html(classes=["table table-bordered table-dark"])
, copy the output (minus the quote marks ipython uses to denote the string type) that into my-file.html
, open that up in a browser and be amazed!
For added effeciency try using pyperclip to copy the output right to your clipboard!
pip install pyperclip
and then pyperclip.copy(df.to_html(classes=["table table-bordered table-dark"]))