【问题标题】:Apply different conditional formatting to different rows将不同的条件格式应用于不同的行
【发布时间】:2019-10-27 16:23:26
【问题描述】:

我通常使用 pandas 在工作簿中生成漂亮的表格输出

如何对每行应用不同的条件格式来突出显示失败的单元格。即对于 R1 行,值 > 3,R2 行值

或者说...对于每一列,其中 R2

R1 = [1,10,3]
R2 = [4,5,6]
E_Rfsw = [7,8,9]

data = [R1, R2,E_Rfsw]
df = pd.DataFrame(data, 
                columns=[V for V in design.Vout],
                index=['FB R1 (kΩ)', 'FB R2 (kΩ)','Fsw resistor (kΩ)'],
                )
display(df.round(4)) 

【问题讨论】:

    标签: python pandas jupyter-lab


    【解决方案1】:

    我相信您需要Styler.apply 的自定义函数:

    def highlight_row(x):
        c1 = 'background-color: red'
    
        df1 = pd.DataFrame('', index=x.index, columns=x.columns)
        #filter index by R1, R2
        m1 = x.index.str.contains('R1')
        m2 = x.index.str.contains('R2')
        #compare filtered rows by conditions and add Falses for all rows
        mask = (x[m1] > 3).append((x[m2] > 5)).reindex(x.index, fill_value=False)
        #set values by mask
        df1 = df1.mask(mask, c1)
        return df1
    df.style.apply(highlight_row, axis=None)
    

    示例数据 - 仅删除了 columns 参数,因为未指定 design.Vout

    【讨论】:

    • 谢谢,这符合我的要求,特别是因为有 20 行,有些与其他相关,有些与阈值相关。让我尝试一下,但我认为就是这样。我试图了解造型器,但我只是不太明白
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多