如何在 pandas 中链接样式函数的条件?

How can I chain the conditions for style functions in pandas?

这就是我想要实现的目标

我有一个 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 个条件,单元格的背景颜色应该不同:
单元格 <= 0 应该是红色的
单元格 >= 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)

它适用于两种情况。

这是我的问题

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

您可以编写一个普通的 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)

输出:

我觉得最简单的方法是使用 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)