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

Pandas表格内容不染色:如何将Styler样式同步到df2img导出图片

问题原因

  1. 染色逻辑错误:你提前将Profit列转为了带%的字符串类型,判断type(s) != str永远不成立,所有值都会被标记为绿色。且你调用df.style.applymap后没有将生成的Styler对象赋值存储,样式直接丢失。
  2. df2img库仅支持传入普通DataFrame对象,无法识别Pandas的Styler样式配置,所以导出的图片没有染色效果。

最简解决方案

直接使用Pandas Styler自带的图片导出能力,不需要额外调整表格生成逻辑,还能完整保留所有样式配置。首先安装依赖:

pip install dataframe-image

然后使用修正后的代码即可:

import pandas as pd
import dataframe_image as dfi

df = pd.DataFrame(
    {
        'Fruits': ['Apple', 'Apple', 'Apple', 'Orange', 'Banana', 'Orange'],
        'BuyPrice': [1000, 3000, 2400, 3000, 800, 1500],
        'SellPrice': [1200, 2800, 2500, 2500, 700, 1750]
    }
)

# 新增利润率列,先保留数值用于判断正负,暂不转字符串
df['Profit'] = (df['SellPrice']-df['BuyPrice'])*100/df['BuyPrice']

# 重命名列名
df = df.rename({'BuyPrice': 'Buy Price', 'SellPrice': 'Sell Price'}, axis=1)

# 高亮正负利润
def highlight_cols(s):
    color = 'red' if s < 0 else 'green'        
    return 'color: %s' % color

# 生成Styler对象,同时配置百分比格式、表头样式、行交替背景
styler = df.style.applymap(highlight_cols, subset=['Profit'])\
    .format({'Profit': '{:,.2f} %'})\
    .set_table_styles([
        {'selector': 'th', 'props': [('color', 'white'), ('background-color', 'orange')]},
        {'selector': 'tr:nth-child(even)', 'props': [('background-color', 'white')]},
        {'selector': 'tr:nth-child(odd)', 'props': [('background-color', 'lightgray')]}
    ])

# 导出为图片
dfi.export(styler, 'table_fruits.png', table_conversion='matplotlib')

运行后导出的图片就会自带正负利润染色效果,完全符合预期样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:06:03