首页 > 解决方案 > 如何在python中有条件地为输出的excel的单元格着色?

问题描述

我必须以这种方式为我的 xls 输出的单元格(仅用于确定的列)着色:

green positive value
gray NaN value
red negative valute

假设我的数据框:

df
     a   b    c    d    e
0    2   8   -8    3   -4
1   -4   2    9    0    NaN
2    1   0    NaN  8    0
3    5   1    7    1    3
4    6   0   -2    4   -2

第 ti 列着色:a、c 和 e。

我的实际代码很简单:

writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer,'Sheet1', index=False)
writer.save()

标签: pythonxlspandas.excelwriter

解决方案


您可以创建一个函数来突出显示...

def color_cells():
    # put your condition here
    return ['background-color: yellow']

然后应用你的突出显示

df.style.apply(color_cells)

查看文档以获取更多信息

例如,您可以突出显示最大值:

def highlight_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

您可以定义自己的条件


推荐阅读