0

How to color the class = Third rows in this following titanic data:

import numpy as np
import pandas as pd
import seaborn as sns

df = sns.load_dataset('titanic')
df.groupby(['sex', 'class']).agg({'fare': ['sum','count']})

References

The official example only deals with simple dataframes, but here I have to highlight multi-index dataframe. I was wondering how to accomplish the task.

Required

I would like two rows where class = Third for male and female to be red.

enter image description here

2 Answers 2

2

If you don't have substring 'Third' in other indexes, you can do this:

df.groupby(['sex', 'class']).agg({'fare': ['sum','count']}).style.apply(lambda ser: ['background: lightblue' if 'Third' in ser.name else '' for _ in ser],axis=1)

enter image description here

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

Comments

1

I already like https://stackoverflow.com/users/5200329/bhishan-poudel 's answer better, but if you want a solution based on what I read on your styling link, the below can work:

def color_third_red(val):
    return [('color: red' if 'Third' in x else 'color: black') for x in val.index]

gdf = df.groupby(['sex', 'class']).agg({'fare': ['sum','count']})

s = gdf.style.apply(color_third_red,axis=0)

s looks like:

enter image description here

Comments

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.