Home » excel » excel – Coloring dataframe before saving

excel – Coloring dataframe before saving

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have created a df where the values are *”Yes”, “No” and “Maybe”.*

I would like to make this cells colorful before saving in excel. If I use the library xlwt, I have something like this:

sheet2.write(row, col, str('Allowed'), style)

However, I don’t want to open the excel again, which it is already created with pandas in order to go through and fill it with my colors. I would like to save my dataframe already with the desired colors formatted in excel.

My dataframe is something like this:

enter image description here

My desired output is:

enter image description here

Any suggestions on how to do this?

How to&Answers:

something like this?

def color_df(val): 
    if val == 'Yes':
        color = 'red'
    elif val == 'Maybe':
        color = 'Orange'
    else:
        color = 'Blue'
    return 'color: %s' % color

df = df.style.applymap(color_df).to_excel(path_var + 'styled.xlsx', engine='xlsxwriter')