pandas 多索引样式突出显示一行

pandas multiindex style highlight a row

如何为 class = 以下巨大数据中的第三行着色:

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']})

参考文献

官方的例子只处理了简单的dataframes,这里要强调一下multi-index 数据框。我想知道如何完成任务。

必填

我想要两行,其中 class = 男性和女性的第三行是红色的。

如果你在其他索引中没有子串'Third',你可以这样做:

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)

我已经更喜欢 https://whosebug.com/users/5200329/bhishan-poudel 的回答了,但是如果你想要一个基于我读到的关于你的样式的解决方案 link,下面的方法可以工作:

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 看起来像: