[英]pandas multiindex style highlight a row
How to color the class = Third rows in this following titanic data:如何着色 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']})
References参考
The official example only deals with simple dataframes, but here I have to highlight multi-index dataframe.官方示例只处理简单的数据帧,但这里我必须强调多索引 dataframe。 I was wondering how to accomplish the task.我想知道如何完成任务。
I would like two rows where class = Third for male and female to be red.我想要两行 class = 第三的男性和女性是红色的。
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:我已经喜欢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
looks like: s
看起来像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.