突出显示中的行擅长使用Python


  1. 我有两个不同的excel用于比较。。。

    在此处输入图像描述

  2. 我想在合并后突出显示Excellence中重复的"名称"one_answers"注册日期"记录。

  3. 我是用错了"熊猫"的功能,还是我的逻辑不正确?

    import pandas as pd 
    dt1 = pd.read_excel('Data1.xlsx')
    dt2 = pd.read_excel('Data2.xlsx')
    meg_rlt = pd.merge(dt1.iloc[:, [0, 1]], dt2.iloc[:, [0, 2]], on=['Name', 'Reg Date'], how='outer', indicator=True)
    for a in meg_rlt.iloc[:, [2]].values:
    if a == 'both':
    return meg_rlt.style.apply[background: green]
    

经过一番研究,我找到了这篇文章。这显示了如何使用应用于颜色行和列
下面的解决方案使用了所描述的方法(请参阅函数bg_color(,应该符合您的需求
生成的Excel文件会突出显示重复的条目

import pandas as pd
dt1 = pd.read_excel('Data1.xlsx')
dt2 = pd.read_excel('Data2.xlsx')
# Rename column to match data2.xlsx
dt1 = dt1.rename({"Student Name": "Name"}, axis='columns')
df_merge = pd.merge(dt1.iloc[:, [0, 1]], dt2.iloc[:, [0, 2]], on=[
'Name', 'Reg Date'], how='outer', indicator=True)
i = 0
rows_to_color = []
for a in df_merge.iloc[:, [2]].values:
if a == 'both':
# remember the rows you want to color
rows_to_color.append(i)
i += 1

def bg_color(col):
color = '#ffff00'
# color every cell, where rows_to_color contains the index
return ['background-color: %s' % color
if i in rows_to_color
else ''
for i, x in col.iteritems()]  # i --> row; x --> value

styled = df_merge.style.apply(bg_color)
styled.to_excel("merged_file_styled.xlsx")

最新更新