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

Pandas 1.5.3转DataFrame为HTML遇CSS格式错误,0.25.1可正常运行

Pandas 1.5.3导出HTML触发ValueError问题

在Pandas 1.5.3版本中执行DataFrame导出HTML操作时,触发ValueError错误,提示内容如下:

ValueError: Styles supplied as string must follow CSS rule formats, for example 'attr: val;'. '#FFFFFF' was given.

但相同代码在Pandas 0.25.1版本中可正常运行。

完整测试代码

import pandas as pd

url_raw = "https://pastebin.com/raw/MGnwCvMk"
re_df = pd.read_csv(url_raw, sep="\t", na_filter=False)

columns_with_color_dictionary = {
    "Seq": "#FFFFFF",
    "Cov": "#FFFFFF",
    "CTer": "#FFFFFF",
    "NTer": "#FFFFFF",
    "B13": "#fc9863",
    "F0": "#fdca93",
    "F1": "#fdbb85",
    "F3": "#fdbd86",
    "F2": "#fdbb85",
    "Y73": "#fda671",
    "Y59": "#f06749",
    "Y58": "#840000",
    "Y45": "#fdd6a3",
    "Y37": "#feeacc",
    "Y26": "#fdb67f",
    "Y24": "#fdaf79",
    "Y13": "#fca36e",
}

def f_color(dat,c='red'):
    return [f'background-color: {c}' if v=='1' else '#FFFFFF' for v in dat]
        
style = re_df.style
style = style.set_properties(width="25px")

for column, color in columns_with_color_dictionary.items():
    style = style.apply(f_color, axis=0, subset=column, c=color)
    
with open("MyTest.html", 'w') as fh:
    fh.write(style.render())

尝试style.to_html()后的错误信息

C:\Users\Admin\AppData\Local\Temp\ipykernel_10844\4235473097.py:31: FutureWarning: this method is deprecated in favour of `Styler.to_html()`
  fh.write(style.render())
Traceback (most recent call last):
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style_render.py:1873 in maybe_convert_css_to_tuples
        return [
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style_render.py:1874 in <listcomp>
        (x.split(":")[0].strip(), x.split(":")[1].strip())
    
IndexError: list index out of range
    
    
During handling of the above exception, another exception occurred:
    
Traceback (most recent call last):
    
  Cell In[76], line 31
    fh.write(style.render())
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style.py:457 in render
    return self._render_html(sparse_index, sparse_columns, **kwargs)
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style_render.py:206 in _render_html
    d = self._render(sparse_index, sparse_columns, max_rows, max_cols, "&nbsp;")
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style_render.py:163 in _render
    self._compute()
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style_render.py:258 in _compute
    r = func(self)(*args, **kwargs)
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style.py:1762 in _apply
    self._update_ctx(result)
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style.py:1585 in _update_ctx
    css_list = maybe_convert_css_to_tuples(c)
    
  File C:\Anaconda3\lib\site-packages\pandas\io\formats\style_render.py:1879 in maybe_convert_css_to_tuples
    raise ValueError(
    
ValueError: Styles supplied as string must follow CSS rule formats, for example 'attr: val;'. '#FFFFFF' was given.

解决方案

问题根源在于f_color函数的else分支仅返回了颜色值#FFFFFF,而Pandas 1.5.3对样式字符串的格式要求更严格,必须是完整的CSS规则(如background-color: #FFFFFF),而非单纯的颜色值。旧版本Pandas允许简化写法,但新版本已不再支持。

修改f_color函数如下:

def f_color(dat,c='red'):
    return [f'background-color: {c}' if v=='1' else 'background-color: #FFFFFF' for v in dat]

同时,建议替换已弃用的style.render()方法,改用style.to_html():

with open("MyTest.html", 'w') as fh:
    fh.write(style.to_html())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:57:49