You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决导出pandas Styler为PNG时的SyntaxError: not a PNG file错误?

问题:导出Pandas Styler对象为PNG时出现"not a PNG file"错误

长期以来,我一直使用以下代码将类型为pandas.io.formats.style.Styler的DataFrame样式对象(df1)导出为PNG文件:

dfi.export(df1, "test.png")

但今日执行代码时:

dfi.export(df1, "ice_cotton_" + str(dashboard_date).split(" ")[0])

出现了如下报错信息:

Traceback (most recent call last):

  File ~\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3369 in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  Input In [48] in <cell line: 1>
    dfi.export(df1, "ice_cotton_" + str(dashboard_date).split(" ")[0])

  File ~\Anaconda3\lib\site-packages\dataframe_image\_pandas_accessor.py:48 in export
    return _export(

  File ~\Anaconda3\lib\site-packages\dataframe_image\_pandas_accessor.py:117 in _export
    img_str = converter(html)

  File ~\Anaconda3\lib\site-packages\dataframe_image\_screenshot.py:188 in run
    img = self.take_screenshot()

  File ~\Anaconda3\lib\site-packages\dataframe_image\_screenshot.py:140 in take_screenshot
    img = mimage.imread(buffer)

  File ~\Anaconda3\lib\site-packages\matplotlib\image.py:1560 in imread
    with img_open(fname) as image:

  File ~\Anaconda3\lib\site-packages\PIL\ImageFile.py:112 in __init__
    self._open()

  File ~\Anaconda3\lib\site-packages\PIL\PngImagePlugin.py:676 in _open
    raise SyntaxError("not a PNG file")

  File <string>
SyntaxError: not a PNG file

解决方法

1. 确保文件名包含.png后缀

你的代码生成的文件名未显式添加PNG后缀,可能导致工具无法识别输出格式。修改代码,手动加上后缀:

# 使用f-string让代码更简洁
date_str = str(dashboard_date).split(" ")[0]
dfi.export(df1, f"ice_cotton_{date_str}.png")

2. 检查日期字符串的合法性

确认str(dashboard_date).split(" ")[0]生成的字符串不含系统禁止的文件名字符(如/、:、*等),可以先打印验证:

date_str = str(dashboard_date).split(" ")[0]
print(date_str)

如果有非法字符,建议用日期格式化方法生成标准格式:

# 假设dashboard_date是datetime对象
date_str = dashboard_date.strftime("%Y-%m-%d")
dfi.export(df1, f"ice_cotton_{date_str}.png")

3. 更新依赖库

如果上述方法无效,可能是依赖库版本问题,尝试更新相关组件:

pip install --upgrade pillow matplotlib dataframe_image

更新后重启Python环境再测试。

4. 替代方案:先存HTML再转PNG

如果直接导出仍有问题,可以先将Styler对象保存为HTML,再转换为PNG:

date_str = str(dashboard_date).split(" ")[0]
# 保存为HTML
df1.to_html(f"temp_{date_str}.html")
# 从HTML导出PNG
dfi.export(f"temp_{date_str}.html", f"ice_cotton_{date_str}.png")

内容的提问来源于stack exchange,提问作者Haikal Yeo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:35:51