通过python Pandas在excel中突出显示两行之间的差异,但突出显示的颜色未显示在excel文件中

kqhtkvqz  于 2023-01-18  发布在  Python
关注(0)|答案(1)|浏览(146)

下面是我的代码:-

import pandas as pd
def highlight_diff_by_column_and_write(dataframe, column, file):
df = dataframe.copy()
for value in df[column].unique():
    matches = df[df[column] == value]
    for index, row in matches.iterrows():
        for index2, row2 in matches.iterrows():
            if index != index2:
                for col in df.columns:
                    if row[col] != row2[col]:
                        df.at[index, col] = 'background-color: #FF0000'
                        df.at[index2, col] = 'background-color: #FF0000'
    df.style.apply(lambda x: ['background: #FF0000' if x.name in matches.index else '' for i in x], axis=1).to_excel(file, engine='openpyxl')


file =('OMS-Diff-Reports_20221223.xlsx')
df = pd.read_excel(file,'TBPCRules')
highlight_diff_by_column_and_write(df, 'UNIQUE_ID', 'result.xlsx')

下面是我得到的结果:-x1c 0d1x
我想用背景色显示差异

qxsslcnc

qxsslcnc1#

要使用to_excel方法突出显示dataframe中的单元格的at方法未进入Excel。
必须使用创建Excel的库,如openpyxl

import openpyxl
from openpyxl.styles import PatternFill

def highlight_diff_by_column_and_write(dataframe, file):
    df = dataframe.copy()
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    for index, row in df.iterrows():
        for index2, row2 in df.iterrows():
            if index != index2:
                for i in range(len(row)):
                    cell1 = sheet.cell(row=index + 1, column=i + 1)
                    cell2 = sheet.cell(row=index2 + 1, column=i + 1)
                    cell1.value = row[i]
                    cell2.value = row2[i]
                    if row[i] != row2[i]:
                        cell1.fill = PatternFill(fgColor="FF0000FF", fill_type="solid")
                        cell2.fill = PatternFill(fgColor="FF0000FF", fill_type="solid")
    workbook.save(file)

相关问题