Search code examples
pythonpandasdataframemulti-index

How can I style Pandas multiindex dataframe columns using threshold conditioning?


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?

enter image description here

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


Solution

  • 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')
    

    enter image description here