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

Python3.7中StyleFrame初始化报错及Excel列宽设置问题求助

解决StyleFrame初始化报错(TypeError: Style frame init doesn't support Styler)的问题

问题根源

  • 执行df = df.style.apply(beatify_output, axis=1)后,变量df已经从pandas DataFrame变成了pandas Styler对象,而StyleFrame的构造函数仅接受原始DataFrame,不支持Styler类型,因此触发报错。
  • 原代码还存在其他语法错误:beatify_output函数中第二个if语句缺少冒号;excel_writer定义行存在语法错误;多余的代码块标记```。

解决方案

放弃混用pandas Styler和StyleFrame,直接用StyleFrame完成行背景色设置+列宽调整的需求,StyleFrame本身提供了样式设置的API,无需依赖pandas的style模块。

修正后的完整代码

from styleframe import StyleFrame, Styler
import pandas as pd

# 读取原始数据,保留DataFrame类型
df = pd.read_csv('final_output.csv')

def expand_columns_size_and_style():
    len_max = 50
    # 初始化StyleFrame,传入原始DataFrame
    sf = StyleFrame(df)
    
    # 定义两种行样式
    pass_style = Styler(bg_color='red')
    fail_style = Styler(bg_color='green')
    
    # 为result为Pass的行设置背景色
    sf.apply_style_by_indexes(
        indexes=sf[sf['result'] == 'Pass'].index,
        styler_obj=pass_style
    )
    # 为result为Fail的行设置背景色
    sf.apply_style_by_indexes(
        indexes=sf[sf['result'] == 'Fail'].index,
        styler_obj=fail_style
    )
    
    # 设置指定列的宽度
    sf.set_column_width(columns=['actual_prompt', 'expected_prompt'], width=len_max)
    
    # 导出到Excel并保存
    sf.to_excel('my_file.xlsx', sheet_name='Sheet1').save()

expand_columns_size_and_style()

关键说明

  • 初始化StyleFrame时必须传入原始pandas DataFrame,不能是Styler对象。
  • 使用StyleFrame的apply_style_by_indexes方法,通过筛选行索引批量设置行样式,替代原有的pandas style.apply逻辑。
  • 将样式设置和列宽调整逻辑合并到同一个函数中,避免多次写入Excel导致内容覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:39:57