Search code examples
pandasstyling

How to make comparison dependent on conditions on the dataframe columns?


I want to highlight cell by cell with some conditions like this: This is output that I want

df = pd.DataFrame(...)

def highlight(row):

    if row[0] > row[1]:
        color = 'red'

    elif row[0] < row[1]:
        color = 'green'

    else:
        color = 'yellow'

    background = ['background-color: {}'.format(color) for row in df['col1']]
    return background


df2 = df.style.apply(highlight, axis = 1)
df2.to_excel('style.xlsx')

By the way, I want to make this comparison between col1 and col2.

I am waiting for your help.


Solution

  • Instead of returning the background for the column, return the rows:

    np.random.seed(1)
    df = pd.DataFrame(np.random.randint(0,3, (10,4)),
                      columns=('hour','col1','col2','col3'))
    
    def highlight(row):
        if row['col1'] > row['col2']:
            color='red'
        elif row['col1'] < row['col2']:
            color='green'
        else: color = 'yellow'
    
        # notice the difference
        # also color:black is not needed, just add because my jupyter style
        background=['',f'background-color:{color}; color:black','','']
        return background
    
    df.style.apply(highlight,axis=1)
    

    Output:

    enter image description here