首页 > 解决方案 > 调用 StyleFrame.apply_style_by_indexes 时如何避免 ValueError?

问题描述

目前我有一个很大的 StyleFrame 对象列表。来自某些数据帧的一些单元格我想根据它们的值为背景着色:> 1 为红色,<=1 为绿色。我认为多次调用“apply_style_by_indexes”方法会创建多个命名样式,我不知道如何避免它。

red_shade = "F85C4D"
    green_shade = "90EE90"
    for key in dataframe_dict_keys:
        sf.apply_style_by_indexes(sf[sf[key] <= threshold],
                                  styler_obj=Styler(bg_color=green_shade),
                                  cols_to_style=key)
        sf.apply_style_by_indexes(sf[sf[key] > threshold],
                                  styler_obj=Styler(bg_color=red_shade),
                                  cols_to_style=key)

调用“.to_excel”方法时引发错误,该方法为多个 StyleFrame 对象调用

 dic["dataframe"].to_excel(writer, sheet_name=country_code, startrow=idx, index=True, best_fit=list(dic["keys"]))

编辑:

    def __apply_colors_based_on_value(self, sf, dataframe_dict_keys, threshold):
        for key in dataframe_dict_keys:
            sf.apply_style_by_indexes(sf[sf[key] <= threshold],
                                      styler_obj=Styler(bg_color="F85C4D",
                                      cols_to_style=key)
            sf.apply_style_by_indexes(sf[sf[key] > threshold],
                                      styler_obj=Styler(bg_color="F85C4D",
                                      cols_to_style=key)

WHERE: sf - StyleFrame 实例,dataframe_dict_keys - StyleFrame 列(标题)列表, dic - dict{“dataframe”:StyleFrame 对象,“keys”:List[str] # 标题列

标签: pythonpython-3.xopenpyxlstyleframe

解决方案


推荐阅读