python - 将新值与以前的值进行比较,如果在 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')
解决方案
这是为单元格设置背景的代码
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
推荐阅读
- python - 如何使用 BeautifulSoup 逐行读取数据?
- c# - 使用 Ifc2x3 获取对象的所有属性
- python - 如何执行 numpy 数组的未排序比较?
- android - 返回小部件时未运行 Future Builder
- typescript - 忽略对打字稿装饰器的覆盖
- powerbi - 如何根据使用 power bi DAX 公式提交的日期中的数字分配 1 st、2 nd、3 rd 等?
- python - 我想将 urdu 抓取数据保存到 csv 文件中,但是当我打开文件时,文件格式不可读
- angular - daterangepicker.component.d.ts:错误无法在环境上下文中声明访问器
- vue.js - 带有子项的 Vuejs 侧边栏菜单
- ios - 使用会话管理器时如何查看访问令牌?