首页 > 解决方案 > 将新值与以前的值进行比较,如果在 Excel 中不相同则标记(使用 Python)

问题描述

我在 Excel 中有一个数据框 df,其中包含我希望与以前的值进行比较的值。如果当前值与之前的值不同,我希望突出显示 excel 中的单元格。

这是我的数据:

COL1  match
9     1  False
8     3  False
2     2  True
3     1  False
4     2  False
5     2  False

期望的结果:

df['match'] = df.COL1.eq(df.COL1.shift())
print (df)


COL1  match
9     1  False
8     3  False
2     2  True
3     1  False
4     2  False
5     2  False

并突出显示 Excel 中的“假”值

这就是我正在做的事情:

import xlsxwriter
workbook = xlsxwriter.Workbook('c:\\temp\\df.xlsx')
worksheet = workbook.add_worksheet()

def highlight_cells():
return ['background-color: yellow']
df.style.apply(highlight_cells)     

df['match'] = df.COL1.eq(df.COL1.shift())

我不确定如何将所有这些放在一起,最终突出显示 Excel 中与先前值不匹配的任何单元格。我目前正在研究。

非常感谢任何建议。

更新

这就是我所做的:

 workbook = xlsxwriter.Workbook('Book1.xlsx')
 worksheet = workbook.add_worksheet()



 cell_format = workbook.add_format()


 cell_format.set_pattern(1)  # This is optional when using a solid fill.
 cell_format.set_bg_color('green')

 for index, row in df.iterrows():
      if row.Row1 == row.Row2:
           worksheet.write("B"+str(index+1), 'Ray', cell_format)  
    
    
    
    
 df.to_excel('test.xlsx')

标签: pythonexcelpandasnumpy

解决方案


这是为单元格设置背景的代码

cell_format = workbook.add_format()

cell_format.set_pattern(1)  # This is optional when using a solid fill.
cell_format.set_bg_color('green')

for index, row in df.iterrows():
    if row.COL1 == row.match:
       worksheet.write("B"+str(index+1), 'Ray', cell_format)    #there you need to put the required cell like A1 or B2 or similar 

文档:https ://xlsxwriter.readthedocs.io/format.html#set_bg_color


推荐阅读