【发布时间】:2019-05-06 10:18:04
【问题描述】:
【问题讨论】:
标签: python python-3.x pandas dataframe comparison
【问题讨论】:
标签: python python-3.x pandas dataframe comparison
使用函数更简洁
def format_df(x):
if x.Date1 != x.Date2:
return ['background-color: red'] * len(x)
return [''] * len(x)
df.style.apply(lambda x: format_df(x), axis=1).to_excel("file.xlsx",index=False)
编辑 1:如果您只想突出显示第二列,
def format_df(x):
if x.Date1 != x.Date2:
return ['']+['background-color: red']
return [''] * len(x)
df.style.apply(lambda x: format_df(x), axis=1)
【讨论】:
two 列。对于多列:例如如果你的Date2 是第四列,那么return ['']*3 + ['background-color: red'] + [''] * (len(x)-4)
在助手 DataFrame 和 export to excel 中创建样式:
df = pd.DataFrame({'Date1':['19/3/2011','15/5/2015','18/8/2018'],
'Date2':['19/3/2011','1/1/2019','18/8/2018']})
print (df)
Date1 Date2
0 19/3/2011 19/3/2011
1 15/5/2015 1/1/2019
2 18/8/2018 18/8/2018
def highlight_diff(x):
c1 = 'background-color: red'
c2 = ''
m = x['Date1'] != x['Date2']
df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
df1.loc[m, :] = c1
return df1
(df.style
.apply(highlight_diff,axis=None)
.to_excel('styled.xlsx', engine='openpyxl', index=False))
【讨论】:
df1.loc[m, :] = c1 更改为df1.loc[m, 'Date2'] = c1
您应该使用DataFrame.style 和DataFrame.to_excel:
import pandas as pd
df = pd.DataFrame({'Date1':['19/3/2011','15/5/2015','18/8/2018'],
'Date2':['19/3/2011','1/1/2019','18/8/2018']})
df.style.apply(lambda x: ['background-color: red']*df.shape[1] if x['Date1'] != x['Date2'] else ['']*df.shape[1], axis=1).to_excel("output.xlsx", index=False)
你会得到:
【讨论】: