Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export pandas Styled table to image file

The code below when run in jupyter notebook renders a table with a colour gradient format that I would like to export to an image file.

The resulting 'styled_table' object that notebook renders is a pandas.io.formats.style.Styler type.

I have not been able to find a way to export the Styler to an image.

I hope someone can share a working example of an export, or give me some pointers.

import pandas as pd import seaborn as sns  data = {('count', 's25'):         {('2017-08-11', 'Friday'): 88.0,         ('2017-08-12', 'Saturday'): 90.0,         ('2017-08-13', 'Sunday'): 93.0},         ('count', 's67'):         {('2017-08-11', 'Friday'): 404.0,         ('2017-08-12', 'Saturday'): 413.0,         ('2017-08-13', 'Sunday'): 422.0},         ('count', 's74'):         {('2017-08-11', 'Friday'): 203.0,         ('2017-08-12', 'Saturday'): 227.0,         ('2017-08-13', 'Sunday'): 265.0},         ('count', 's79'):         {('2017-08-11', 'Friday'): 53.0,         ('2017-08-12', 'Saturday'): 53.0,         ('2017-08-13', 'Sunday'): 53.0}}  table = pd.DataFrame.from_dict(data) table.sort_index(ascending=False, inplace=True)  cm = sns.light_palette("seagreen", as_cmap=True) styled_table = table.style.background_gradient(cmap=cm) styled_table 

enter image description here

like image 234
user1243477 Avatar asked Aug 13 '17 20:08

user1243477


People also ask

How do you save a DataFrame as a picture?

Pass your normal or styled DataFrame to the export function along with a file location to save it as an image. You may also export directly from the DataFrame or styled DataFrame using the dfi. export and export_png methods, respectively. Here, an example of how exporting a DataFrame would look like in a notebook.

Can I store images in pandas DataFrame?

It is possible to wrap the images in a python list. That makes it possible to store it in a pandas DataFrame.


1 Answers

As mentioned in the comments, you can use the render property to obtain an HTML of the styled table:

html = styled_table.render() 

You can then use a package that converts html to an image. For example, IMGKit: Python library of HTML to IMG wrapper. Bear in mind that this solution requires the installation of wkhtmltopdf, a command line tool to render HTML into PDF and various image formats. It is all described in the IMGKit page.

Once you have that, the rest is straightforward:

import imgkit imgkit.from_string(html, 'styled_table.png') 
like image 60
Shovalt Avatar answered Oct 22 '22 19:10

Shovalt