【问题标题】:How to use Pandas stylers for coloring an entire row based on a given column?如何使用 Pandas 样式器根据给定列为整行着色?
【发布时间】:2022-01-26 19:51:44
【问题描述】:

我一直在尝试将 Pandas 数据框打印到 html 并突出显示特定的整行,如果该行的一个特定列的值超过阈值。我已经查看了 Pandas Styler Slicing 并试图改变 highlight_max 函数来实现这种用途,但似乎失败得很惨;例如,如果我尝试用检查给定行的值是否高于所述阈值来替换 is_max(例如,像

is_x = df['column_name'] >= threshold

),目前还不清楚如何正确传递这样的东西或返回什么。

我也尝试过使用 df.loc 在别处简单地定义它,但效果也不太好。

另一个问题也出现了:如果我之后删除该列(目前的标准),样式是否仍然有效?我想知道 df.loc 是否会阻止这样的事情成为问题。

【问题讨论】:

  • 好吧,我想我有你的解决方案,可以根据超过一个值的一列或多列突出显示整行。

标签: python pandas pandas-styles


【解决方案1】:

如果列中的值超过阈值,此解决方案允许您传递列标签或列标签列表以突出显示整行。

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

def highlight_greaterthan(s, threshold, column):
    is_max = pd.Series(data=False, index=s.index)
    is_max[column] = s.loc[column] >= threshold
    return ['background-color: yellow' if is_max.any() else '' for v in is_max]


df.style.apply(highlight_greaterthan, threshold=1.0, column=['C', 'B'], axis=1)

输出:

或者一列

df.style.apply(highlight_greaterthan, threshold=1.0, column='E', axis=1)

【讨论】:

  • 改用['background-color: yellow' if is_max.any() else ''] * len(is_max) 来评估is_max.any() 条件一次。
【解决方案2】:

这是一个更简单的方法:

  1. 假设您有一个 100 x 10 的数据框,df。还假设您要突出显示与列对应的所有行,例如“duration”,大于 5。

  2. 您首先需要定义一个突出显示单元格的函数。真正的诀窍是您需要返回一行,而不是单个单元格。例如:

    def highlight(s):
        if s.duration > 5:
            return ['background-color: yellow'] * len(s)
        else:
            return ['background-color: white'] * len(s)
    

**注意返回部分应该是10个的列表(对应列数)。这是关键部分。

  1. 现在您可以将其应用于数据框样式:

    df.style.apply(highlight, axis=1)
    

【讨论】:

  • 不用硬编码 10,你可以只使用 len(s) 来考虑任何宽度的数据帧
猜你喜欢
  • 2018-10-21
  • 2017-07-03
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多