I’m trying to highlight specific cells for each column with different condition which their value matches the condition for each row.
Below image is what I want to achieve: The table I attempt to achieve
I searched google and stackoverflow but none of these can meet my requirement. Can anyone who’s familiar with Pandas Style could assist?
Below are the codes I tried and failed:
Ex1
JavaScript
x
7
1
import pandas as pd
2
df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list("ABC"))
3
4
def highlight(s):
5
return ['background-color: yellow' if (v>2) else 'background-color: white' for v in s]
6
df.style.apply(highlight, axis=0)
7
Ex2
JavaScript
1
6
1
import pandas as pd
2
df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list("ABC"))
3
4
Column_limit = (df['A'] > 6) | (df['B'] > 2) | (df['C'] < 3)
5
df[Column_limit].style.applymap(lambda x: 'background-color: yellow', subset=pd.IndexSlice[:, ['A', 'C']])
6
Ex3
JavaScript
1
6
1
import pandas as pd
2
df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list("ABC"))
3
4
subsets = pd.IndexSlice[:, 'A']
5
df.style.applymap(lambda x: 'background-color: yellow', subset = subsets)
6
Advertisement
Answer
If there is same number of conditions like some number of columns use:
JavaScript
1
16
16
1
df = pd.DataFrame([[10,3,1], [3,7,2], [2,4,4]], columns=list("ABC"))
2
3
def highlight(x):
4
c1 = 'background-color: yellow'
5
6
# condition
7
m = pd.concat([(x['A'] > 6), (x['B'] > 2), (x['C'] < 3)], axis=1)
8
#print (m)
9
#empty DataFrame of styles
10
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
11
#set new columns by condition
12
return df1.mask(m, c1)
13
14
15
df.style.apply(highlight, axis=None)
16
If there is a lot of columns and need processing only some of them:
JavaScript
1
15
15
1
def highlight(x):
2
c1 = 'background-color: yellow'
3
4
#empty DataFrame of styles
5
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
6
#set new columns by condition
7
8
df1.loc[(x['A'] > 6), 'A'] = c1
9
df1.loc[(x['B'] > 2), 'B'] = c1
10
df1.loc[(x['C'] < 3), 'C'] = c1
11
12
return df1
13
14
df.style.apply(highlight, axis=None)
15
EDIT:
If need specified all masks but in last step filter only some columns use:
JavaScript
1
15
15
1
def highlight(x):
2
c1 = 'background-color: yellow'
3
4
#empty DataFrame of styles
5
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
6
#set new columns by condition
7
8
df1.loc[(x['A'] > 6), 'A'] = c1
9
df1.loc[(x['B'] > 2), 'B'] = c1
10
df1.loc[(x['C'] < 3), 'C'] = c1
11
12
need = ['A','C']
13
df1 = df1[need].reindex(x.columns, fill_value='', axis=1)
14
return df1
15
Or remove masks which not necessary:
JavaScript
1
14
14
1
def highlight(x):
2
c1 = 'background-color: yellow'
3
4
#empty DataFrame of styles
5
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
6
#set new columns by condition
7
8
df1.loc[(x['A'] > 6), 'A'] = c1
9
df1.loc[(x['C'] < 3), 'C'] = c1
10
11
return df1
12
13
df.style.apply(highlight, axis=None)
14