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

这就是我想要实现的目标

我确实有一个 Pandas Dataframe - 例如这个:


            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 样式中的信息:


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)

它适用于两种情况。


这是我的问题

我尝试了不同的方法将第三个条件添加到上面的函数中,但总是返回错误。

您能给我提示如何在列表中添加条件吗?

我没有找到答案。多谢。


Smart猫小萌
浏览 119回答 2
2回答

泛舟湖上清波郎朗

您可以编写普通的 for 循环而不是列表理解。def highlight_number(row):&nbsp; &nbsp; arr = []&nbsp; &nbsp; for cell in row:&nbsp; &nbsp; &nbsp; &nbsp; if&nbsp; cell <= 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.append('background-color: red; color: white')&nbsp; &nbsp; &nbsp; &nbsp; elif cell >= 100:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.append('background-color: blue; color: white')&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.append('background-color: white; color: black')&nbsp; &nbsp; return arrdf.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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python