Reputation: 105
I'm trying to highlight some values in some columns in data frame using pandas styles like:
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4),
columns=list('BCDE'))],axis=1)
df.iloc[0, 2] = np.nan
def highlight_greater(row):
color=""
if row['B'] > row['C']:
color = 'red'
elif row['D'] > row['E']:
color = 'gray'
background = ['background-color: {}'.format(color) for _ in row]
return background
with open ('out.html','w') as out:
print >> out, df.style.apply(highlight_greater, axis=1).render()
That's work fine, but not correspond to my objectif, i want only to highlight B and D columns. This script highlight all the columns in the row if match condition. Any Idea ? Thanks
Upvotes: 3
Views: 4613
Reputation: 862441
You can change custom function for DataFrame of styles:
def highlight_greater(x):
r = 'red'
g = 'gray'
m1 = x['B'] > x['C']
m2 = x['D'] > x['E']
df1 = pd.DataFrame('background-color: ', index=x.index, columns=x.columns)
#rewrite values by boolean masks
df1['B'] = np.where(m1, 'background-color: {}'.format(r), df1['B'])
df1['D'] = np.where(m2, 'background-color: {}'.format(g), df1['D'])
return df1
df.style.apply(highlight_greater, axis=None)
Upvotes: 5