如何给类着色=在下面的数据中的第三行:
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']})
参考文献
官方示例只处理简单的数据帧,但在这里我不得不突出强调多索引数据帧。 我在想如何完成这项任务。
我想要两行,其中阶级=第三个为男性和女性是红色的。
如果在其他索引中没有子字符串'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
类似于: