提问者:小点点

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


如何给类着色=在下面的数据中的第三行:

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

参考文献

  • https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
  • Pandas multiindex column Styler

官方示例只处理简单的数据帧,但在这里我不得不突出强调多索引数据帧。 我在想如何完成这项任务。

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


共2个答案

匿名用户

如果在其他索引中没有子字符串'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://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类似于: