1

我想根据在另一个等长列表中找到的值将不同的背景颜色应用于 DataFrame 上的列。我的数据(这是一个玩具示例)具有以下结构:

Username    Password    Indications New_name    Mr/Mrs  Balance
Carlos       xxx         LoreIpsum  Corona      Mrs     100
Daniel       yyy         LoreIpsum  Corona      Mrs     200
Guille       zzz         LoreIpsum  Corona      Mrs     300

我正在开发一个测试自动化框架。在某些时候,我需要从网站读取值(余额列)并将其与我从 excel 中读取的值进行比较。在我这样做之后,我将 True 或 False 附加到列表中。因此,如果前两个读取值等于我的电子表格上的数据,但第三个是错误的,我的列表将如下所示:

In:  Print(checkList)
Out: [True, True, False]

我找到了如何通过以下命令将样式应用于一行:

df.style.applymap(lambda x: 'background-color: red' if Condition else 'background-color: green', subset=['Balance'])

我的问题是我不知道如何迭代行以及带有布尔值的列表,在上面的代码行中,对所有行都应用了相同的条件。如有必要,我可以提供进一步的解释。

4

2 回答 2

2

您可以按条件创建DataFrame由 s 填充的background-color,例如从您的列表中Styler.apply

checkList =  [True, True, False]

def highlight(x):
    c1 = 'background-color: red'
    c2 = 'background-color: green' 

    #if necessary pass condition
    #checkList = x['Balance'] < 300
    #empty DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    #set Balance column by condition in list (necessary same length like df)
    df1['Balance'] = np.where(checkList, c1, c2)
    return df1


df.style.apply(highlight, axis=None)
于 2020-04-15T13:35:52.640 回答
0

如果@jezrael 解决方案返回:(TypeError:_translate() 缺少 2 个必需的位置参数:'sparse_index' 和 'sparse_cols')

将 pandas 降级到 1.2.4 版本可能是一个临时解决方案......

# Uninstall any pandas library installed:
pip uninstall pandas

# After uninstalling pandas, install pandas==1.2.4
pip install pandas==1.2.4

然后,您可以尝试创建DataFrame由 s 填充background-color的条件,例如从您的列表中Styler.apply,作为@jezrael 解决方案。

使用df.loc代替的替代解决方案np.where

checkList =  [True, True, False]

def highlight(x):
   c1 = 'background-color: red'
   c2 = 'background-color: green'

   # If necessary pass condition 
   checkList =  x['Balance'] <= 300
   checkList2 = x['Balance'] > 300
   
  # Empty DataFrame of styles
  df1 = pd.DataFrame(x, index=x.index, columns=x.columns)

  #set Balance column by condition in checkList (using df1.loc instead of np.where)
  df1.loc[checkList, 'Balance'] = c1
  df1.loc[chekcList2, 'Balance'] = c2

  # Return styled dataset
  return df1

# To apply highlight styler:
df.style.apply(highlight, axis=None)
于 2021-08-04T21:00:35.447 回答