EricA
EricA

Reputation: 403

Highlight text and column in python

styling text and column in python

sample snippet from data frame

df1 = {
    'IncNum':['1','2','3'],
    'Text_Col':['sample text','sample text containing the keywords to be highlighted','highlighted values'],
    'Outcome': ['True','False','True']
}

df1 = pd.DataFrame(df1)

I am trying to highlight a specific row and some keywords in Text_Col any pointers on how to achieve the same

keywords = ['sample ','text'] --> should be color coded for column Text_col

def highlight(s):
    if s.Outcome == "True":
        return ['background-color: yellow']*len(df1.columns)
    else:
        return ['background-color: white']*len(df1.columns)

df1.style.apply(highlight, axis=1)

Upvotes: 0

Views: 399

Answers (1)

jezrael
jezrael

Reputation: 862511

Use Styler.apply with function for return DataFrame of styles, also check if not boolean values in Outcome - then solution is necessary use m1 = x['Outcome']:

def color(x): 
   c1 = 'background-color: yellow'
   c = ''

   #if True are strings
   m1 = x['Outcome'] == "True"

   #if True are boolean
   #m1 = x['Outcome']

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

df1.style.apply(color,axis=None)

Upvotes: 1

Related Questions