【问题标题】:Export pandas Styled table to image file将熊猫样式表导出到图像文件
【发布时间】:2018-01-21 16:50:55
【问题描述】:

下面的代码在 jupyter notebook 中运行时会呈现一个我想导出到图像文件的颜色渐变格式的表格。

notebook 呈现的“styled_table”对象是 pandas.io.formats.style.Styler 类型。

我无法找到将 Styler 导出到图像的方法。

我希望有人可以分享一个导出的工作示例,或者给我一些指示。

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

【问题讨论】:

标签: python pandas jupyter-notebook seaborn pandas-styles


【解决方案1】:

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

html = styled_table.render()

然后您可以使用将 html 转换为图像的包。例如,IMGKit: Python library of HTML to IMG wrapper。请记住,此解决方案需要安装 wkhtmltopdf,这是一个将 HTML 渲染为 PDF 和各种图像格式的命令行工具。这一切都在 IMGKit 页面中进行了描述。

有了这些,剩下的就很简单了:

import imgkit
imgkit.from_string(html, 'styled_table.png')

【讨论】:

  • 我收到此错误If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - http://wkhtmltopdf.org 你知道我该如何解决吗?
  • @EnzoDtz 似乎没有安装 wkhtmltopdf,或者无法通过系统路径访问它。您需要能够在命令行中输入例如wkhtmltopdf --help 并查看帮助菜单。
  • 如果其他人不想处理安装,@Shovalt 的进程可以在您的浏览器中使用,并利用 MyBinder.org 系统从here 启动活动的 Jupyter 会话。
  • 我可以找到该可执行文件的 pdf,但找不到图像
  • 这就是答案。我的 jupyter 是从服务运行的,我使用了 os.system(echo $PATH) 并看到没有,尽管我自己使用 which(wkhtmltopdf) 看到了它。所以是的,一旦我将 environmentPath... yada yada 添加到我的 .service 文件中,jupyter 就正确地选择了路径。
【解决方案2】:

您可以使用来自https://github.com/dexplo/dataframe_image 的dexplo 的dataframe_image。安装包后,它还允许您将样式器对象保存为来自README 的示例中的图像:

import numpy as np
import pandas as pd
import dataframe_image as dfi

df = pd.DataFrame(np.random.rand(6,4))
df_styled = df.style.background_gradient()

dfi.export(df_styled, 'df_styled.png')

【讨论】:

  • 之前的答案丢失了很多格式,这个解决方案可以完美地工作。旁注:我必须先升级 pip,然后才能使用 pip install --upgrade pip 安装此软件包。
  • 截至 2021 年,这应该是最佳答案。相比imgkit的方案,它模仿了Jupyter的风格,不需要外部依赖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 2013-06-12
  • 1970-01-01
  • 2019-04-27
相关资源
最近更新 更多