'pandas multiindex style highlight a row
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.
Solution 1:[1]
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)
Solution 2:[2]
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BhishanPoudel |
| Solution 2 |



