首页 > 解决方案 > 根据条件为选定列的行着色

问题描述

我找到了为数据框的行着色的解决方案。但它为所有列着色。我需要的是为数据框的列组着色。在下面的函数中,我希望能够选择要着色的列。

df =  pd.DataFrame({'A':[23,25,10], 'B':[7,8,3], 'C':[8,3,1]})
print (df)
    A  B  C
0  23  7  8
1  25  8  3
2  10  3  1

def highlight_col(x):
#copy df to new - original data are not changed
df = x.copy()
#set by condition
mask =  df['A'].between(10 , 21 , inclusive=True)
mask2 = df['A'].between(22 , 26 , inclusive=False)
df.loc[mask, :] = 'background-color: yellow'
df.loc[mask2,:] = 'background-color: red'
return df    

df.style.apply(highlight_col, axis=None)   


# So instead of df.loc[mask, :] I would like to do : df.loc[mask, ['A', 'B']] for example. 
# So I can create another mask for C column and so on.
# Hope it is clear that I don't need subset=IndexSlice
dff.style.apply(highlight_col3, subset=pd.IndexSlice[:, ['A', 'B']], axis=None)
# This will not do the job. Because then I can not color C column differently.

标签: pythonpandasstyling

解决方案


创建助手DataFrame并选择列以更改颜色loc

def highlight_col(x):
    #set by condition
    mask =  df['A'].between(10 , 21 , inclusive=True)
    mask2 = df['A'].between(22 , 26 , inclusive=False)
    x = pd.DataFrame('', index=df.index, columns=df.columns)
    x.loc[mask, ['A', 'B']] = 'background-color: yellow'
    x.loc[mask2,['A', 'B']] = 'background-color: red'
    return x    

图片


推荐阅读