pandas:excel 输出中的彩色单元格取决于列值

pandas: coloured cells in excel output depending on column values

我想使用 pandas 将数据框导出到 excel 并且我想根据第一列添加颜色(奇数 -> 颜色 A,偶数 -> 颜色 B) .

我在下面有一个小例子,它不会产生任何错误,但是生成的 excel 文件的单元格中没有颜色。知道为什么会这样吗?我正在使用 Python 3.7.4 和 Pandas 0.24.2。谢谢。

import pandas as pd

df = pd.DataFrame({'Data': [1, 1, 2, 2, 3, 4, 4, 5, 5, 6]})

writer = pd.ExcelWriter('/tmp/pandas_conditional3.xlsx', engine='xlsxwriter')

df.to_excel(writer, sheet_name='Sheet1', index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']

format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})
format2 = workbook.add_format({'bg_color': '#C6EFCE',
                               'font_color': '#006100'})

worksheet.conditional_format('A1:A8', {'type':     'cell',
                                       'criteria': '=MOD(ROW(),2)',
                                       'value': 0,
                                       'format':   format1})
worksheet.conditional_format('A1:A8', {'type':     'cell',
                                       'criteria': '=MOD(ROW(),2)',
                                       'value': 1,
                                       'format':   format2})

writer.save()

您需要将 conditional_formattype 更改为 formula:

worksheet.conditional_format('A1:A8', {'type':     'formula',
                                       'criteria': '=MOD(ROW(),2)=0',
                                       'format':   format1})
worksheet.conditional_format('A1:A8', {'type':     'formula',
                                       'criteria': '=MOD(ROW(),2)=1',
                                       'format':   format2})