【问题标题】:Highlight row based on boolean column基于布尔列突出显示行
【发布时间】:2021-06-07 12:21:25
【问题描述】:

有一个数据框,我为其创建了布尔列“延迟提交”,其中“真”表示迟到,“假”表示准时。

我想用红色突出显示“True”行,用绿色突出显示“False”,但我似乎无法让它工作,因为我对 Python 还是很陌生。我已经尝试了下面的代码,有什么想法为什么它不起作用?

def highlight_late(s):
    if s['Late Submission'] == True:
        return 'background-color: red'
    elif s['Late Submission'] == False:
        return 'background-color: green'
    
df7.style.apply(highlight_late, axis = 1)

给出的错误是:

Result has shape: (281556,)
Expected shape:   (281556, 6)

提前致谢

【问题讨论】:

  • 根据 API 文档,func 应该采用 Series 或 DataFrame(取决于轴),并返回具有相同形状的对象。你的函数返回一个标量。

标签: python pandas boolean highlight


【解决方案1】:

我使用这个简单的df 来展示它是如何工作的,基于这个pandas doc

import pandas as pd
import numpy as np
df = pd.DataFrame({'a': np.random.randint(0, 10, 10), 'b': np.random.randint(0, 10, 10), 'late': np.random.choice([0, 1], 10).astype(np.bool)})

这给了我们:

|    |   a |   b | late   |
|---:|----:|----:|:-------|
|  0 |   3 |   2 | False  |
|  1 |   1 |   0 | False  |
|  2 |   3 |   6 | False  |
|  3 |   0 |   1 | True   |
|  4 |   6 |   7 | True   |
|  5 |   0 |   0 | False  |
|  6 |   0 |   7 | False  |
|  7 |   6 |   4 | True   |
|  8 |   7 |   0 | True   |
|  9 |   7 |   7 | False  |

现在我们使用一个函数来应用样式:

def highlight_late(s):
    return ['background-color: red' if s_ else 'background-color: green' for s_ in s]

然后:

df.style.apply(highlight_late, subset=['late'])

结果:

【讨论】:

    【解决方案2】:

    从 Albo 借用样本 df。 如果要为整行着色,可以将代码修改为:

    def highlight_late(s):
        return ['background-color: red' if s['late'] else 'background-color: green' for s_ in s]
    
    df.style.apply(highlight_late, axis=1)
    

    这会给你:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 2016-03-10
      • 1970-01-01
      • 2018-07-05
      • 2015-04-12
      • 2021-12-23
      • 2022-11-15
      • 1970-01-01
      相关资源
      最近更新 更多