Anudocs
Anudocs

Reputation: 686

Highlighting rows using index numbers in pandas dataframe

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?

Upvotes: 0

Views: 775

Answers (1)

jezrael
jezrael

Reputation: 863531

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))

Upvotes: 1

Related Questions