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:
JavaScript
x
8
1
def highlight_cells(StartingDataFrame):
2
if StartingDataFrame[StartingDataFrame['HRC'].str.contains("HRC")]:
3
return ['background-color: red']*5
4
else:
5
return ['background-color: white']*5
6
7
StartingDataFrame.style.apply(highlight_cells, axis=1)
8
but it doesn’t seem to do anything to the cells. Is there anything i am doing wrong?
Code:
JavaScript
1
17
17
1
StartingDataFrame = pd.DataFrame({'HRC':['aaa','HRD ','HRC oo'],
2
'A':[1,2,3]})
3
4
5
def highlight_cells(x):
6
c1 = 'background-color: red'
7
c = 'background-color: white'
8
9
#if True are strings
10
m1 = StartingDataFrame['HRC'].str.contains("HRC")
11
12
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
13
df1.loc[m1, 'HRC'] = c1
14
return df1
15
StartingDataFrame.style.apply(highlight_cells,axis=None)
16
StartingDataFrame.to_excel("outputTest.xlsx")
17
Advertisement
Answer
You can use custom function for create DataFrame of styles:
JavaScript
1
18
18
1
StartingDataFrame = pd.DataFrame({'HRC':['aaa','HRD ','HRC oo'],
2
'A':[1,2,3]})
3
4
5
def highlight_cells(x):
6
c1 = 'background-color: red'
7
c = 'background-color: white'
8
9
#if True are strings
10
m1 = StartingDataFrame['HRC'].str.contains("HRC", na=False)
11
12
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
13
df1.loc[m1, 'HRC'] = c1
14
return df1
15
16
(StartingDataFrame.style.apply(highlight_cells,axis=None)
17
.to_excel("outputTest.xlsx", index=False))
18
Another solution is slect columns for test values by in
:
JavaScript
1
7
1
def highlight_cells(val):
2
color = 'red' if 'HRC' in val else 'white'
3
return f'background-color: {color}'
4
5
(StartingDataFrame.style.applymap(highlight_cells, subset=['HRC'])
6
.to_excel("outputTest.xlsx", index=False))
7
EDIT: In your solution need assign back:
JavaScript
1
3
1
styles = StartingDataFrame.style.apply(highlight_cells,axis=None)
2
styles.to_excel("outputTest.xlsx")
3