pandas 将熊猫样式表导出到图像文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45664519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export pandas Styled table to image file
提问by user1243477
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.
下面的代码在 jupyter notebook 中运行时呈现了一个带有颜色渐变格式的表格,我想将其导出到图像文件中。
The resulting 'styled_table' object that notebook renders is a pandas.io.formats.style.Styler type.
notebook 呈现的结果“styled_table”对象是 pandas.io.formats.style.Styler 类型。
I have not been able to find a way to export the Styler to an image.
我还没有找到将 Styler 导出为图像的方法。
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
回答by Shovalt
As mentioned in the comments, you can use the render
property to obtain an HTML of the styled table:
如评论中所述,您可以使用该render
属性获取样式表的 HTML:
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.
然后,您可以使用将 html 转换为图像的包。例如,IMGKit:HTML 到 IMG 包装器的 Python 库。请记住,此解决方案需要安装wkhtmltopdf,这是一种将 HTML 呈现为 PDF 和各种图像格式的命令行工具。这一切都在 IMGKit 页面中进行了描述。
Once you have that, the rest is straightforward:
一旦你有了它,剩下的就很简单了:
import imgkit
imgkit.from_string(html, 'styled_table.png')