0

I am trying to highlight complete row based on index values. Here is what i did:

df = pd.read_excel(module)
rows = df.index[df['MYCOLUMN'].str.contains(command, na=False)].tolist()

if rows: 
        df.style.apply(lambda x: ['background: red' if x.name in rows else '' for i in x], axis=1)
        df.to_excel(module, index = False) 

But the row is not getting highligted and the formatting of my excel is also changed. Can someone tell the right way of doing this?

1
  • use openpyxl.. its much better for such works Commented Feb 10, 2020 at 12:59

1 Answer 1

1

You can create DataFrame of styles with Styler.apply and set rows by masks with loc:

def color(x): 
   c1 = 'background-color: red'
   c = ''
   m1 = df['MYCOLUMN'].str.contains(command, na=False)

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[m1, :] = c1
   return df1

(df.style.apply(color,axis=None)
         .to_excel('styled.xlsx', engine='openpyxl', index=False))

For me working variables outside function like:

def color(x): 
   c = ''
   m1 = df['MYCOLUMN'].str.contains(command, na=False)

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[m1, :] = c1
   return df1

command = 'test'
c1 = 'background-color: red'

(df.style.apply(color, axis=None)
         .to_excel('styled.xlsx', engine='openpyxl', index=False))
Sign up to request clarification or add additional context in comments.

1 Comment

How to pass a variable in function 'color'??

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.