猿问

pandas multiindex 样式高亮一行


如何为类着色 = 以下泰坦尼克号数据中的第三行:


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 多索引列样式器

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


必需的

我想要两行,其中 class = Third for male 和 female 是红色的。

动漫人物
浏览 254回答 2
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)

ITMISS

我已经更喜欢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好像:
随时随地看视频慕课网APP

相关分类

Python
我要回答