17

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

is_x = df['column_name'] >= threshold

),目前尚不清楚如何正确传递这样的事情或返回什么。

我也尝试过使用 df.loc 在其他地方简单地定义它,但这也不是很好。

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

4

2 回答 2

34

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

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)

在此处输入图像描述

于 2017-04-25T03:23:20.547 回答
15

这是一个更简单的方法:

  1. 假设您有一个 100 x 10 的数据框 df。还假设您要突出显示与列对应的所有行,例如“持续时间”,大于 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)
    
于 2018-01-17T17:07:36.327 回答