Skip to main content
 首页 » 编程设计

python之Pandas 到 Excel 条件格式整列

2024年09月07日14开发

我想将 Pandas 数据框写入带有格式的 Excel。为此,我使用了 xlsxwriter。我的问题是双重的:

  • 首先,如何将条件格式应用于整列?在examples他们使用特定的单元格范围格式(例如 worksheet1.conditional_format('B3:K12', ...)),有没有办法引用整列?

    <
  • 其次,如果 B 列与 C 列的差异超过 15%,我想用红色标记它。正确的公式是什么?

我目前正在尝试下面的代码,但它不起作用(我不知道如何引用列)。

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()  

此外,我在 Mac 上运行 Excel,不确定是否有任何区别,但我注意到 Windows 版本使用 , 的地方,Mac 版本需要 ; 用于公式。不知道这对 xlsxwriter 有何影响。

请您参考如下方法:

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

您可以指定列中从第一行到最后一行的单元格范围,如 C1:C1048576。这是它在内部的存储方式,它只是显示为 C:C。

这适用于可以在 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?

这是您应该在 Excel 中弄清楚的内容,然后将条件格式应用于 XlsxWriter。像这样的东西可能会起作用:

=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

参见 Working with Formulas XlsxWriter 文档的部分解释了如何使用它。