Pandas 到 Excel 条件格式整列
Pandas to Excel conditional formatting whole column
我想将 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
请参阅 XlsxWriter 文档的 Working with Formulas 部分,了解如何使用它。
我想将 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
请参阅 XlsxWriter 文档的 Working with Formulas 部分,了解如何使用它。