根据条件为选定列的行着色

时间:2018-06-05 11:58:51

标签: python pandas styling

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

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.

1 个答案:

答案 0 :(得分:0)

创建帮助器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    

pic