Python - Using pandas to format excel cell

后端 未结 3 1969
梦谈多话
梦谈多话 2020-12-15 02:09

I have a pandas dataframe, which is something like shown below.

I would like to format the column \"Pass/Fail\" as if Fail --> red background, else

3条回答
  •  不知归路
    2020-12-15 02:32

    Disclaimer: I wrote the following library

    I'd like to suggest using StyleFrame:

    import pandas as pd
    from StyleFrame import StyleFrame, Styler
    
    df = pd.DataFrame({'Pass/Fail':['Pass','Fail','Fail'],
                       'expect':[1,2,3]})
    
    sf = StyleFrame(df)
    
    sf.apply_style_by_indexes(sf[sf['Pass/Fail'] == 'Pass'], cols_to_style='Pass/Fail',
                              styler_obj=Styler(bg_color='green'))
    sf.apply_style_by_indexes(sf[sf['Pass/Fail'] == 'Fail'], cols_to_style='Pass/Fail',
                              styler_obj=Styler(bg_color='red'))
    
    sf.to_excel('test.xlsx').save()
    

    Since it bridges the gap between pandas and openpyxl, the styling is done on the dataframe level instead of the worksheet level (so for example you don't need to know the relevant cell range is B2:B4 or mess with indexes.

    The code above outputs the following:

    EDIT: Just saw you mentioned you've tried to install but got an error. Can you edit your question and include the error?

提交回复
热议问题