Highlight cell on condition

后端 未结 2 515
礼貌的吻别
礼貌的吻别 2021-01-27 00:32

I\'m trying to highlight all cells that are before the current date. However I am highlighting all cells instead of just the old dates.

import pandas as pd
from         


        
2条回答
  •  醉话见心
    2021-01-27 01:06

    Idea is create new DataFrame filled by styles by condition with Styler.apply, for set rows by conditions is used numpy.where:

    def expired(x):
        c1 = 'background-color: red'
        c2 = 'background-color: green'
    
        df1 = pd.DataFrame('', index=x.index, columns=x.columns)
        m = x['Expiration Date'] < today
        df1['Expiration Date'] = np.where(m, c1, c2)
        return df1
    
    df.style.apply(expired, axis=None)
    

    If coloring all rows by condition use DataFrame.mask:

    def expired(x):
        c1 = 'background-color: red'
        c2 = 'background-color: green'
    
        df1 = pd.DataFrame(c1, index=x.index, columns=x.columns)
        m = x['Expiration Date'] < today
        df1 = df1.mask(m, c2)
        return df1
    

提交回复
热议问题