qhan
qhan

Reputation: 97

How to color pandas table by comparing two columns

For example, I have a dataframe with two columns A and B. If A > B, I want to color the row red; if A <= B, I want to color that row green. Any idea how can I do this? Thanks!

Upvotes: 3

Views: 3996

Answers (1)

jack6e
jack6e

Reputation: 1522

From the docs:

def highlight_greater(row):

    if row['A'] > row['B']:
        color = 'red'
    elif row['A'] <= row['B']:
        color = 'green'

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

    return background

df.style.apply(highlight_greater, axis=1)

Upvotes: 9

Related Questions