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!
-
pandas.pydata.org/pandas-docs/stable/style.htmlMaxU - stand with Ukraine– MaxU - stand with Ukraine2017-06-27 20:55:29 +00:00Commented Jun 27, 2017 at 20:55
-
1I've read it. But all its examples take only one value. I want to know how can I compare two values from the dataframe.qhan– qhan2017-06-27 20:57:32 +00:00Commented Jun 27, 2017 at 20:57
Add a comment
|
1 Answer
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)
2 Comments
qhan
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!
jack6e
Sorry, forgot to return a color value for each column in the row. Updated - let me know if that works.