I think you can use Slicing in Styles
for select columns B
and C
and then Styler.applymap
for elementwise styles.
import pandas as pd
import numpy as np
data = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)
def highlight_cols(s):
color="grey"
return 'background-color: %s' % color
data.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['B', 'C']])
If you want more colors or be more flexible, use Styler.apply(func, axis=None)
, the function must return a DataFrame
with the same index and column labels:
import pandas as pd
import numpy as np
data = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)
def highlight_cols(x):
#copy df to new - original data are not changed
df = x.copy()
#select all values to default value - red color
df.loc[:,:] = 'background-color: red'
#overwrite values grey color
df[['B','C']] = 'background-color: grey'
#return color df
return df
data.style.apply(highlight_cols, axis=None)