2

在我的代码中,我使用 df.style.applymap() 将 HTML 呈现到我的 Intranet 网页上。我有以下代码对我来说效果很好,(2 列被传递给我的函数 highlight_vals)。

def highlight_vals(val, color='green', color1='red'):
        if val > 0.8:
            return 'background-color: %s' % color
        elif val < -0.9:
            return 'background-color: %s' % color1
        else:
            return ''

现在,我想制作一个类似的功能(或曾经使用当前的 highlight_vals)以实现比较突出显示,条件如下:
if ValinColumn1 > 0.25 * ValinColumn2: # (For same Row/Record)
return 'background-颜色:%s' % 颜色 #Yellow/Highlights。


我在views.py中使用了上面的函数:
httresp += df.style.applymap(highlight_vals,subset=[col1,col2])

4

2 回答 2

5

您需要用于apply(axis=1)遍历行:

def highlight_vals(row, cols=['A', 'B'], color='green'):
    a, b = cols
    styles = {col: '' for col in row.index}
    if row[a] > 0.25 * row[b]:
        styles[a] = 'background-color: %s' % color
        styles[b] = 'background-color: %s' % color
    return styles

df.style.apply(lambda x: highlight_vals(x, cols=['B', 'E']), axis=1)

在此处输入图像描述

于 2018-09-27T05:10:21.740 回答
0

从这个问题: Pandas 中 map、applymap 和 apply 方法之间的区别 我认为你需要的是函数 apply。它可以在多个列上工作。您正在使用面向整个数据框的 applymap(但是您可以通过使用 df.style 从数据框中选择一列来解决这个问题)

这是一个玩具示例:

>>> df = pd.DataFrame([[1,2],[3,4]], columns=['A', 'B'])
>>> df['sum_A_B']=df.apply(lambda x: x['A'] + x['B'], axis=1)
>>> df
   A  B  sum_A_B
0  1  2        3
1  3  4        7
于 2018-09-27T03:50:41.780 回答