熊猫多索引样式突出显示一行

时间:2020-07-11 14:31:33

标签: python pandas

如何在以下钛酸数据中为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']})

参考

官方示例仅处理简单的数据框,但是在这里我必须强调多索引 数据框。我想知道如何完成任务。

必需

我想要两行,其中class = Third,男性和女性为红色。

enter image description here

2 个答案:

答案 0 :(得分:3)

如果其他索引中没有子字符串“ 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)

enter image description here

答案 1 :(得分:1)

我已经更喜欢https://stackoverflow.com/users/5200329/bhishan-poudel的答案了,但是如果您想要基于我在样式链接上阅读的内容的解决方案,则可以使用以下方法:

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如下:

enter image description here