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

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169

2 Answers2

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

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169
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

lytseeker
  • 305
  • 4
  • 10