Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...