繁体   English   中英

如何使用 Pandas 样式器根据给定的列为整行着色?

[英]How to use Pandas stylers for coloring an entire row based on a given column?

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

is_x = df['column_name'] >= threshold

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

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

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

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

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)

在此处输入图片说明

这是一个更简单的方法:

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

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

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

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

  1. 现在您可以将其应用于数据框样式,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM