Skip to main content
 首页 » 编程设计

python之如何根据值为 Python Pandas 中的整行着色

2025年01月19日11kevingrace

所以我想出了如何使用 pandas 中的 Style 模块为单个单元格和列着色。但是,我想根据该行中单个单元格中的值为整行着色。

例如,如果 A 列中的单元格 C 的值为 23,则将 C 的行涂成黄色。

我该怎么做?

请您参考如下方法:

使用:

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'] == 23 
    df.loc[mask, :] = 'background-color: yellow' 
    df.loc[~mask,:] = 'background-color: ""' 
    return df     
 
df.style.apply(highlight_col, axis=None)