首页 > 解决方案 > 如何根据 Pandas 中的行和列值突出显示单元格?

问题描述

我试图突出显示我的行名和行值。

如果 currentRatio 和超过 1.4 突出显示红色

如果 quickRatio 和超过 32 突出显示黄色

我无法让我的第一个测试正确运行。

import pandas as pd

df1 = pd.DataFrame({'currentRatio' : [1.2, 1.5, 1.4, 2.0],
                    'quickRatio' : [30, 37, 30, 35], })
print(df1.T)

这个输出

                 0     1     2     3
currentRatio   1.2   1.5   1.4   2.0
quickRatio    30.0  37.0  30.0  35.0
def color_row(row):
    pprint(row)
    if row.name == 'currentRatio:
        if row.value > 1.4:
            return pd.Series('background-color: red', row.index)

 display(df1.style.apply(color_row, axis=1))

pprint 行输出为

index          currentRatio
0         1.2
1         1.5
2         1.14
3         1.2
4         1.352669417512594

谢谢你的时间我有任何帮助

标签: pythonpandasdataframeformatting

解决方案


您可以使用适当的条件逻辑作为列表理解

df1 = pd.DataFrame({'currentRatio' : [1.2, 1.5, 1.4, 2.0],
                    'quickRatio' : [30, 37, 30, 35], })

def color_row(row):
    return ['background-color: red' if v>=1.4 and i=="currentRatio" 
            else 'background-color: yellow' if v>=32 and i=="quickRatio" 
            else ""
            for i, v in row.items()]

df1.style.apply(color_row, axis=1)

推荐阅读