如何使用Python Pandas Stylers根据给定的列为整行着色? [英] How to use Python Pandas Stylers for coloring an entire row based on a given column?

查看:1335
本文介绍了如何使用Python Pandas Stylers根据给定的列为整行着色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将Pandas数据框打印为html,并且如果该行的某一特定列的值超过阈值,则将特定的整个行突出显示.我已经浏览了Pandas Styler Slicing,并尝试为这种用法改变highlight_max函数,但似乎失败了;如果我尝试用检查给定行的值是否高于上述阈值(例如

I've been trying to print out a Pandas dataframe to html and have specific entire rows highlighted if the value of one specific column's value for that row is over a threshold. I've looked through the Pandas Styler Slicing and tried to vary the highlight_max function for such a use, but seem to be failing miserably; if I try, say, to replace the is_max with a check for whether a given row's value is above said threshold (e.g., something like

is_x = df['column_name'] >= threshold

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

), it isn't apparent how to properly pass such a thing or what to return.

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

I've also tried to simply define it elsewhere using df.loc, but that hasn't worked too well either.

另一个问题也浮出水面:如果此后放下该列(当前为标准),样式是否仍然有效?我想知道df.loc是否可以防止此类问题成为问题.

Another concern also came up: If I drop that column (currently the criterion) afterwards, will the styling still hold? I am wondering if a df.loc would prevent such a thing from being a problem.

推荐答案

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

This solution allows for you to pass a column label or a list of column labels to highlight the entire row if that value in the column(s) exceeds the threshold.

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)

这篇关于如何使用Python Pandas Stylers根据给定的列为整行着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆