pythonpandasstyleframe

TypeError: Style frame __init__ doesn't support Styler


So I have a dataframe with multiple columns and I am converting that dataframe to excel in my first function which is beautify_output where I add colour to the entire row based on the value of the result column.

The next function is where I am facing problems, when I try to run the code, I keep getting an error whenever I try to initialise sf=StyleFrame(df). What I'm trying to do in this function is expand the width of the columns in the excel for some columns. Here is the full code. I am on python 3.7

from styleframe import StyleFrame
import pandas as pd

df = pd.read_csv('final_output.csv')


def beatify_output(row):

 if row['result'] == 'Pass':
  return ['background-color: red'] * len(row)
 if row['result'] == 'Fail'
  return ['background-color: green'] * len(row)

df = df.style.apply(beatify_output, axis=1)

df.to_excel('my_file.xlsx',sheet_name='Sheet1')```

def expand_columns_size():
    
     len_max = 50
    
     excel_writer = 
      StyleFrame.ExcelWriter('my_file.xlsx')
    
     sf = StyleFrame(df)
    
       
     sf.set_column_width(columns=['actual_prompt', 'expected_prompt'], width=len_max)
    
     sf.to_excel(excel_writer=excel_writer)
    
     excel_writer.save()
    
expand_columns_size()

Solution

  • The error is due to the fact that styleframe does not know how to handle pandas' styler objects as it has its own way of expressing styles.

    Since you are already using styleframe it would be easier to do all the styling with it.

    import pandas as pd
    
    from styleframe import StyleFrame, Styler
    
    df = pd.read_csv('final_output.csv')
    sf = StyleFrame(df)
    sf.apply_style_by_indexes(sf[sf['result'] == 'Pass'], Styler(bg_color="green"))
    sf.apply_style_by_indexes(sf[sf['result'] == 'Fail'], Styler(bg_color="red"))
    
    # If there are ONLY 'Pass'/'Fail' values in 'result' column we can use
    # sf.apply_style_by_indexes(
    #     indexes_to_style=sf[sf['result'] == 'Pass'],
    #     styler_obj=Styler(bg_color="green"),
    #     complement_style=Styler(bg_color="red")
    # )
    
    len_max = 50
    sf.set_column_width(columns=['actual_prompt', 'expected_prompt'], width=len_max)
    sf.to_excel('my_file.xlsx').close()  # or .save() if close() raises an AttributeError
    

    outputs

    enter image description here