Python - Using pandas to format excel cell

后端 未结 3 1954
梦谈多话
梦谈多话 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条回答
  •  Happy的楠姐
    2020-12-15 02:45

    If have one or more columns and more than two values to format, and want to apply multiple format rules at once then you can do the following:

    def fmt(data, fmt_dict):
        return data.replace(fmt_dict)
    
    styled = df.style.apply(fmt, fmt_dict=fmt_dict, subset=['Test_1', 'Test_2' ])
    styled.to_excel('styled.xlsx', engine='openpyxl')
    

    Above, fm_dict is a dictionary with the values mapped to the corresponding format:

    fmt_dict = {
        'Pass': 'background-color: green',
        'Fail': 'background-color: red',
        'Pending': 'background-color: yellow; border-style: solid; border-color: blue'; color: red,
    }
    

    Notice that for the 'Pending' value, you can also specify multiple format rules (e.g. border, background color, foreground color)

    (Requires: openpyxl and jinja2)


    Here is a full running example:

    import pandas as pd
    
    df = pd.DataFrame({'Test_1':['Pass','Fail', 'Pending', 'Fail'],
                       'expect':['d','f','g', 'h'],
                       'Test_2':['Pass','Pending', 'Pass', 'Fail'],
                      })
    
    fmt_dict = {
        'Pass': 'background-color: green',
        'Fail': 'background-color: red',
        'Pending': 'background-color: yellow; border-style: solid; border-color: blue; color:red',
    }
    
    def fmt(data, fmt_dict):
        return data.replace(fmt_dict)
    
    styled = df.style.apply(fmt, fmt_dict=fmt_dict, subset=['Test_1', 'Test_2' ])
    styled.to_excel('styled.xlsx', engine='openpyxl')
    

提交回复
热议问题