0

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
1
  • 1
    The frame.append method is deprecated and will be removed from pandas in a future version. One might want to change df_all = df_all.append(df_temp) to df_all = pd.concat([df_all, df_temp], axis=0). Commented Oct 5, 2022 at 11:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, how does this change, if I want to highlight only 'D' and not 'E'?
@Bravo Use slice_ = idx[idx[:, :, 'C2'], ['D']].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.