【问题标题】:Pandas - How to Save A Styled Dataframe to ImagePandas - 如何将样式化的数据框保存到图像
【发布时间】:2022-01-01 03:30:20
【问题描述】:

我已经设置了一个数据框输出的样式,并让它在 Jupyter Notebook 中显示我想要的方式,但是我遇到了问题,找到了一种将其保存为图像的好方法。我已经尝试过https://pypi.org/project/dataframe-image/,但我的工作方式似乎是一个 NoneType 因为它是一个样式器对象,并且在尝试使用这个库时会出错。

这只是整个代码的一个sn-p,这是为了循环几个'col_names',我想将它们保存为图像(解释一些编码)。

import pandas as pd
import numpy as np

col_name = 'TestColumn'

temp_df = pd.DataFrame({'TestColumn':['A','B','A',np.nan]})

t1 = (temp_df[col_name].fillna("Unknown").value_counts()/len(temp_df)*100).to_frame().reset_index()
t1.rename(columns={'index':' '}, inplace=True)
t1[' '] = t1[' '].astype(str) 

display(t1.style.bar(subset=[col_name], color='#5e81f2', vmax=100, vmin=0).set_table_attributes('style="font-size: 17px"').set_properties(
    **{'color': 'black !important',
       'border': '1px black solid !important'}
).set_table_styles([{
    'selector': 'th',
    'props': [('border', '1px black solid !important')]
}]).set_properties( **{'width': '500px'}).hide_index().set_properties(subset=[" "], **{'text-align': 'left'}))

[输出]

【问题讨论】:

  • df.style.set_properties 等返回一个样式对象,它有一个render 方法。如果您使用html_str = df.style.render(),那么html_str 是一个有效的html 字符串(尝试打印它)。 Python/Pandas 不会渲染该图片,实际上是您的浏览器执行此操作。也就是说,您可以使用该 html 来呈现并转换为图像,例如this question,或将其保存为 html 扩展名(可能需要一些额外的包装)并稍后使用浏览器打开。
  • 这能回答你的问题吗? Export pandas Styled table to image file

标签: python pandas dataframe


【解决方案1】:

能够更改我在样式器对象上使用 dataframe-image 的方式并使其正常工作。将它传递给 export() 函数而不是直接从对象中调用它似乎是正确的方法。

.render() 确实获得了 HTML,但在将其转换为图像或不使用 Ipython HTML 显示查看时,通常会丢失大部分样式。请参阅下面的比较。

工作代码:

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

col_name = 'TestColumn'

temp_df = pd.DataFrame({'TestColumn':['A','B','A',np.nan]})

t1 = (temp_df[col_name].fillna("Unknown").value_counts()/len(temp_df)*100).to_frame().reset_index()
t1.rename(columns={'index':' '}, inplace=True)
t1[' '] = t1[' '].astype(str) 


style_test = t1.style.bar(subset=[col_name], color='#5e81f2', vmax=100, vmin=0).set_table_attributes('style="font-size: 17px"').set_properties(
    **{'color': 'black !important',
       'border': '1px black solid !important'}
).set_table_styles([{
    'selector': 'th',
    'props': [('border', '1px black solid !important')]
}]).set_properties( **{'width': '500px'}).hide_index().set_properties(subset=[" "], **{'text-align': 'left'})

dfi.export(style_test, 'successful_test.png')

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2022-10-05
    • 2014-09-28
    • 2013-11-12
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多