0

I have a dataframe with a few columns (one boolean and one numeric). I want to put conditional formatting using pandas styling since I am going to output my dataframe as html in an email, based on the following conditions: 1. boolean column = Y and 2. numeric column > 0.

For example,

col1 col2
 Y    15
 N    0
 Y    0
 N    40
 Y    20

In the example above, I want to highlight the first and last row since they meet those conditions.

BENY
  • 317,841
  • 20
  • 164
  • 234
Rafid Reaz
  • 117
  • 2
  • 10
  • https://stackoverflow.com/questions/41203959/conditionally-format-python-pandas-cell – BENY Mar 23 '20 at 17:21

2 Answers2

0

Yes, there is a way. Use lambda expressions to apply conditions and dropna() function to disclude None/NaN values:

df["col2"] = df["col2"].apply(lambda x:x if x > 0 else None)
df["col1"] = df["col1"].apply(lambda x:x if x == 'Y' else None)
df.dropna()
Guy_g23
  • 316
  • 2
  • 7
  • Thanks for the suggestion. However, I am looking to use the style function. Essentially to be able to do this df.style.apply(lambda x: ["background: red" if Col1 == "Y" and Col2 > 0], axis = 1). Can you please help with the syntax on this? – Rafid Reaz Mar 23 '20 at 18:14
0

I used the following and it worked:

def highlight_color(s): if s.Col2 > 0 and s.Col1 == "N": return ['background-color: red'] * 7 else: return ['background-color: white'] * 7

df.style.apply(highlight_color, axis=1).render()

Rafid Reaz
  • 117
  • 2
  • 10