将 pandas 样式表导出到图像文件 [英] Export pandas Styled table to image file

查看:244
本文介绍了将 pandas 样式表导出到图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在jupyter笔记本中运行时,将以我要导出到图像文件的颜色渐变格式呈现表格.

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.

笔记本生成的最终"styled_table"对象是pandas.io.formats.style.Styler类型.

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

我一直无法找到将Styler导出到图像的方法.

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

推荐答案

如注释中所述,您可以使用render属性获取样式表的HTML:

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

html = styled_table.render()

然后,您可以使用将html转换为图像的包.例如, IMGKit:HTML到IMG包装程序的Python库.请记住,此解决方案需要安装 wkhtmltopdf ,这是一种将HTML呈现为PDF和各种图像格式的命令行工具.所有这些都在IMGKit页面中进行了描述.

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

这篇关于将 pandas 样式表导出到图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆