I have dataframe where I have 2 Date columns. I have to compare them and if they are different then whole row should be colored. Please check the picture.
Please guide me how can I do that in python. Thanks in advance.
Advertisement
Answer
Create styles in helper DataFrame and export to excel:
JavaScript
x
22
22
1
df = pd.DataFrame({'Date1':['19/3/2011','15/5/2015','18/8/2018'],
2
'Date2':['19/3/2011','1/1/2019','18/8/2018']})
3
4
print (df)
5
Date1 Date2
6
0 19/3/2011 19/3/2011
7
1 15/5/2015 1/1/2019
8
2 18/8/2018 18/8/2018
9
10
def highlight_diff(x):
11
c1 = 'background-color: red'
12
c2 = ''
13
m = x['Date1'] != x['Date2']
14
15
df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
16
df1.loc[m, :] = c1
17
return df1
18
19
(df.style
20
.apply(highlight_diff,axis=None)
21
.to_excel('styled.xlsx', engine='openpyxl', index=False))
22