如何為類著色 = 以下泰坦尼克號數據中的第三行:import numpy as npimport pandas as pdimport seaborn as snsdf = sns.load_dataset('titanic')df.groupby(['sex', 'class']).agg({'fare': ['sum','count']})參考https://pandas.pydata.org/pandas-docs/stable/user_guide/style.htmlpandas 多索引列樣式器官方的例子只處理簡單的dataframe,這里我要強調一下multi-index dataframe。我想知道如何完成任務。必需的我想要兩行,其中 class = Third for male 和 female 是紅色的。
2 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超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)

ITMISS
TA貢獻1871條經驗 獲得超8個贊
我已經更喜歡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好像:
添加回答
舉報
0/150
提交
取消