Pandas to Excel conditional formatting whole colum

2019-05-24 13:35发布

问题:

I want to write a Pandas dataframe into Excel with formatting. For this I'm using xlsxwriter. My question is twofold:

  • First, how can I apply conditional formatting to a whole column? In the examples they use specific cell-range formatting (eg. worksheet1.conditional_format('B3:K12', ...)), is there a way I can reference a whole column?

  • Second, I want to mark the column B with red if it differs from column C by more than 15%. What would be the correct formula for this?

I'm currently trying the below code, which doesn't work (I don't know how to reference columns).

writer = pd.ExcelWriter('pacing.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Last year vs. current state')
#worksheet.set_column('B:B', 18, format1)
workbook  = writer.book
worksheet = writer.sheets['Last year vs. current state']
format_missed = workbook.add_format({'bg_color': '#ff0000'})
format_ok = workbook.add_format({'bg_color': '#008000'})

worksheet.conditional_format('C:C', {'type':     'formula',
                                        'criteria': '=ABS((B-C)/C) > 15',
                                        'format':   format_missed})
writer.save() 

Also, I'm running Excel on a Mac, not sure if it makes any difference, but I've noticed where the Windows version uses ,, the Mac version needs ; for formulas. Don't know how this affects xlsxwriter.

回答1:

First, how can I apply conditional formatting to a whole column

You can specify the cell range from the first to the last row in the column like C1:C1048576. This is how it is stored internally, it is just displayed as C:C.

This applies to all cases where a column range can be used in XlsxWriter.

Second, I want to mark the column B with red if it differs from column C by more than 15%. What would be the correct formula for this?

That is something you should figure out in Excel and then apply the conditional format to XlsxWriter. Something like this will probably work:

=ABS(B1-C1)/C1 > 0.15

Also, I'm running Excel on a Mac, not sure if it makes any difference, but I've noticed where the Windows version uses ,, the Mac version needs ; for formulas. Don't know how this affects xlsxwriter

See the Working with Formulas section of the XlsxWriter docs for an explanation of how to work with this.