I got one multiindex dataframe as below.
I would like to highlight all the "diff" columns, with different background colors on negative/positive values.
e.g. something like
if '-' in diff.value:
'background-color: lightgreen'
else:
'background-color: pink'
How do I write a styler for it?
I see another similar issue in pandas multiindex style highlight a row
But my dataframe seems not able to groupby as the recommendation in that thread.
Also the method in that thread does not contain threshold conditioning
You can use subset to highlight the row which contains -
def highlight_minus(row):
return np.where(row.astype(str).str.contains('-'),
'background-color: lightgreen',
'background-color: pink')
idx = pd.IndexSlice
slice_ = idx[:, idx[:,'diff']]
s = df.style.apply(highlight_minus, axis=1, subset=slice_)
s.to_html('76374687.html')