3

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!

2

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer! When I tried it, an error occurred: ValueError: Function <function highlight_greater at 0x0000027925CD7620> returned the wrong shape. Result has shape: (417,) Expected shape: (417, 2) 417 is the number of rows in my dataframe and 2 is the number of columns. Do you have any idea why the result does not have a shape (417,2)? Thanks!
Sorry, forgot to return a color value for each column in the row. Updated - let me know if that works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.