Home > other >  How to highlight columns inside multiindex in a pandas dataframe?
How to highlight columns inside multiindex in a pandas dataframe?

Time:10-05

I wish to highlight 'C2' and the values corresponding to 'C2' in columns 'D' and 'E'. I have difficulty as this is a multiindex, and subset selection of columns is not obvious.

df_all = pd.DataFrame()
for i in range(3):
    df_temp = pd.DataFrame(
        data={'D': [0, 23*i, 19*i],
              'E': [18*i, 90*i, -29*i]
        },
        index=pd.MultiIndex.from_tuples([(0, 1, 'C1'), (3, 4, 'C2'), (6, 8, 'C3')], names=["A", "B", "C"])
    )
    df_all = df_all.append(df_temp)

df_all

CodePudding user response:

Let's try

idx = pd.IndexSlice
slice_ = idx[idx[:, :, 'C2'], :]

def highlight_c2(s):
    return ['background-color: #ffffb3;' if v == 'C2' else '' for v in s]

s = (df_all.style
     .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)
     .apply_index(highlight_c2, axis=0, level=[2])
     )
s.to_html('73959317.html')

enter image description here

  • Related