Skip to content
Advertisement

Color in cell containing a string Pandas

i am trying to change the background color in my dataframe if a column contains a certain string however i cant seem to get it to work. I have the following code so far:

def highlight_cells(StartingDataFrame):
    if StartingDataFrame[StartingDataFrame['HRC'].str.contains("HRC")]:
        return ['background-color: red']*5
    else:
        return ['background-color: white']*5

StartingDataFrame.style.apply(highlight_cells, axis=1)

but it doesn’t seem to do anything to the cells. Is there anything i am doing wrong?

Code:

StartingDataFrame = pd.DataFrame({'HRC':['aaa','HRD ','HRC oo'],
                              'A':[1,2,3]})


def highlight_cells(x): 
   c1 = 'background-color: red'
   c = 'background-color: white'

   #if True are strings
   m1 = StartingDataFrame['HRC'].str.contains("HRC")

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[m1, 'HRC'] = c1
   return df1
StartingDataFrame.style.apply(highlight_cells,axis=None)
StartingDataFrame.to_excel("outputTest.xlsx")  

Advertisement

Answer

You can use custom function for create DataFrame of styles:

StartingDataFrame = pd.DataFrame({'HRC':['aaa','HRD ','HRC oo'],
                                  'A':[1,2,3]})


def highlight_cells(x): 
   c1 = 'background-color: red'
   c = 'background-color: white'

   #if True are strings
   m1 = StartingDataFrame['HRC'].str.contains("HRC", na=False)

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

(StartingDataFrame.style.apply(highlight_cells,axis=None)
                  .to_excel("outputTest.xlsx", index=False))

Another solution is slect columns for test values by in:

def highlight_cells(val):
    color = 'red' if 'HRC' in val else 'white'
    return f'background-color: {color}' 

(StartingDataFrame.style.applymap(highlight_cells, subset=['HRC'])
                  .to_excel("outputTest.xlsx", index=False))

EDIT: In your solution need assign back:

styles = StartingDataFrame.style.apply(highlight_cells,axis=None)
styles.to_excel("outputTest.xlsx")  
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement