Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas to Excel conditional formatting whole column

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.

like image 918
lte__ Avatar asked Oct 16 '22 20:10

lte__


1 Answers

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.

like image 150
jmcnamara Avatar answered Oct 21 '22 00:10

jmcnamara