【问题标题】:DataFrame Styling based on conditions for groups of columns基于列组条件的 DataFrame 样式
【发布时间】:2018-04-21 09:50:28
【问题描述】:

我需要为 Dataframe 设置样式:

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 以检查它们是否相等,然后将突出显示/颜色应用于不相等的值

喜欢:

df[['A','B','C']].eq(df.iloc[:, 0], axis=0)

     A       B       C
0   True    True    True
1   True    True    False
2   True    True    True

我无法将 df.style 应用到 df 的子集,然后再进行 concat。

回复@jezrael 的回答:

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为需要:

    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)
    

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

    def highlight(x):
        c = 'background-color: '
        cols = {'red': ['A','B','C'], 'blue':['D','E']}
    
        m = pd.concat([x[v].eq(x[v[0]], axis=0).applymap({False:c+k, True:''}.get) 
                       for k, v in cols.items()], axis=1)
        return m
    

    编辑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)
    

    【讨论】:

    • 知道了!如果我需要为不同的组使用不同的颜色呢? @jezrael
    • 我复制粘贴的你的代码。但是我收到一个值错误Result of <function highlight at 0x000000000D11E908> must have identical index and columns as the input@jezrael
    • @SharvariGc - 你的熊猫版本是什么?对我来说,它在 pandas 0.22.0 中运行良好。
    • @SharvariGc - 请检查替代解决方案
    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多