Python Pandas DataFrame和Excel:添加单元格背景色

问题描述:

当前,我以这种方式保存数据框

Currently I save my dataframe like this

writer = ExcelWriter('test.xlsx')
test_df.to_excel(writer,'Sheet1')
writer.save()

生成的excel文件看起来像这样

And resulted excel file looks like this

cus  1  abc 2 jbd 3 lkl ...
1   col  v  v  v  v  v ...
2    v   v col v  v  v ... 
3    v   v  v  v col v ...

我需要的是,当cus value == header值时,该单元格应该具有绿色背景.在上面的示例中,所有值为"col"的单元格应设置为绿色背景.我该怎么办?

What I need is that, when cus value == header value, that cell should have a green background. In example above, all cells with value 'col' should be set green background. How can I do this?

There is a new feature in Pandas 0.20.0 - Excel output for styled DataFrames:

styled = (df.style
            .applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else ''))
styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')

结果: