【问题标题】:Color formatting excel file row in python在python中颜色格式化excel文件行
【发布时间】:2019-05-06 10:18:04
【问题描述】:

我有数据框,其中有 2 个日期列。我必须比较它们,如果它们不同,那么整行应该是彩色的。请检查图片。

请指导我如何在 python 中做到这一点。提前致谢。

【问题讨论】:

    标签: python python-3.x pandas dataframe comparison


    【解决方案1】:

    使用函数更简洁

    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)
    

    【讨论】:

    • 是否可以只为第二个日期列的第二个单元格着色。
    • 它引发了一些值错误:“ValueError: arrays must be all be same length”
    • @Abdulla,你有多少列,第二个代码仅适用于two 列。对于多列:例如如果你的Date2 是第四列,那么return ['']*3 + ['background-color: red'] + [''] * (len(x)-4)
    【解决方案2】:

    在助手 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))
    

    【讨论】:

    • 是否可以只为日期 2 列的第二个单元格着色?
    • @Abdullah - 当然,将df1.loc[m, :] = c1 更改为df1.loc[m, 'Date2'] = c1
    • @Abdullah - 接受符合您的新要求的答案?
    【解决方案3】:

    您应该使用DataFrame.styleDataFrame.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)
    

    你会得到:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 2016-12-30
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      相关资源
      最近更新 更多