基于列组条件的数据帧样式

2024-04-25 01:55:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要设置数据帧的样式:

df = DataFrame({'A':['Bob','Rob','Dob'],'B':['Bob', 'Rob','Dob'],'C':['Bob','Dob','Dob'],'D':['Ben','Ten','Zen'],'E':['Ben','Ten','Zu']})
df
     A  B    C  D   E
0   Bob Bob Bob Ben Ben
1   Rob Rob Dob Ten Ten
2   Dob Dob Dob Zen Zu

我需要同时比较A、B、C列,检查它们是否相等,然后对不相等的值应用高亮显示/颜色。 然后我需要比较D列和E列,检查它们是否相等,然后对不相等的值应用高亮显示/颜色

比如:

^{pr2}$

我不能申请数据框样式先是df的子集,然后是concat。在

对@jezrael的答复: enter image description here


Tags: 数据dataframedf颜色样式子集bobben
1条回答
网友
1楼 · 发布于 2024-04-25 01:55:25

我认为需要:

def highlight(x):
    c1 = 'background-color: red'
    c2 = '' 
    #define groups of columns for compare by first value of group ->
    #first with A, second with D
    cols = [['A','B','C'], ['D','E']]

    #join all masks together
    m = pd.concat([x[g].eq(x[g[0]], axis=0) for g in cols], axis=1)
    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    df1 = df1.where(m, c1)
    return df1

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

pic

编辑:对于多种颜色,可以按颜色创建字典,并使用列进行比较:

^{pr2}$

pic2

编辑1:

替代方案:

def highlight(x):
    c = 'background-color: '
    cols = {'red': ['A','B','C'], 'blue':['D','E']}

    df1 = pd.DataFrame(c, index=x.index, columns=x.columns)

    for k, v in cols.items():
        m = x[v].eq(x[v[0]], axis=0).reindex(columns=x.columns, fill_value=True)
        df1 = df1.where(m, c+k)
    return df1    

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

相关问题 更多 >