如何使用pandas在条件下应用不同的样式

2024-09-30 14:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据另一个等长列表中的值,对数据帧上的列应用不同的背景色。我的数据(这是一个玩具示例)具有以下结构:

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'])

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


Tags: 数据falsetrue示例列表username结构color
2条回答

如果@jezrael solution返回:(TypeError:_translate()缺少2个必需的位置参数:“稀疏索引”和“稀疏列”)

将熊猫降级到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

然后,您可以尝试创建由background-color按条件填充的DataFrame,例如从^{}中的列表中创建@jezrael solution

使用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)

您可以根据条件创建由background-color填充的DataFrame,例如从^{}中的列表:

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)

相关问题 更多 >