【问题标题】:How can I chain the conditions for style functions in pandas?如何链接 pandas 中样式函数的条件?
【发布时间】:2021-01-19 16:33:14
【问题描述】:

这就是我想要实现的目标

我确实有一个 Pandas 数据框 - 例如这个:

            0           1           2
0  110.718803  119.821042  -52.593518
1   65.180254   33.518722  -69.893688
2 -135.652788  -64.711718 -241.717819
3  237.781393  -56.865142   15.969767
4  141.585158  138.904568 -115.155063
5   10.030938  -59.274415   73.328127
6  106.937681   -3.604859   44.418938
7  -49.478211  -91.574908  160.340627
8  170.744019  -85.764809  246.141857
9  -94.246832   81.069700 -113.460438

基于 3 个条件,单元格的背景颜色应该不同:
单元格 单元格 >= 100 应为蓝色
所有其他单元格

我就是这样做的

我编写了这个函数(基于 Pandas 文档Pandas styling 中的信息:

def highlight_number(row):
    return [
        'background-color: red; color: white' if cell <= 0
        else 'background-color: green; color: white'
        for cell in row
    ]


df.style.apply(highlight_number)

它适用于两种情况。

这是我的问题

我尝试了不同的方法将第三个条件添加到上面的函数中,但我总是得到一个错误。
您能告诉我如何在列表中添加条件吗?
我没有找到答案。非常感谢。

【问题讨论】:

    标签: python pandas dataframe pandas-styles


    【解决方案1】:

    我觉得最简单的方法是使用np.select,它接受一个条件列表和一个选择列表(比如 if elif 并且也像 else 一样采用默认值)并修改你的函数并在 axis=None 上使用它,因为我们正在应用于整个数据框(请注意,您也可以将subset 用于列的子集)

    def highlight_number(dataframe):
        
        conditions = [dataframe <=0,(dataframe>0) & (dataframe>=100)] #your conditions
        choices = ['background-color: red; color: white',
                   'background-color: blue; color: white']
        arr = np.select(conditions,choices,'background-color: white; color: black')
        return pd.DataFrame(arr,index=dataframe.index,columns=dataframe.columns)
    
    
    df.style.apply(highlight_number,axis=None)
    

    【讨论】:

    • 这实现了一个非常灵活的解决方案,因为它可以用于列的子集(与第一个答案相反)。但它需要额外导入 Numpy。
    【解决方案2】:

    您可以编写一个普通的 for 循环而不是列表推导式。

    def highlight_number(row):
        arr = []
        for cell in row:
            if  cell <= 0:
                arr.append('background-color: red; color: white')
            elif cell >= 100:
                arr.append('background-color: blue; color: white')
            else:
                arr.append('background-color: white; color: black')
        return arr
    df.style.apply(highlight_number)
    

    输出:

    【讨论】:

    • 是的:按照我的出发点,迭代并将彩色单元格附加到一个空列表中。
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多