如果数字等于,则为彩色背景单元格

2024-06-12 02:59:43 发布

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

我目前可以使用以下代码更改单元格的背景:

def my_func_blue(val):
    if val in techniques:
        color = 'green'
        return f'background-color: {color}'
    elif val in Fulltechniques:
        color = 'red'
        return f'background-color: {color}'
s = df1.style.applymap(my_func_blue)
s

我希望能够将另一个IF语句添加到

"if val in techniques" 

因此,如果出现次数大于1,则应用颜色:

DF:

Technique_Name  Technique_ID    SOC Alarm   Occurance
0   Sudo and Sudo Caching   T1548.003   002 1
1   Elevated Execution with Prompt  T1548.004   003 1
13  Cloud Account   T1087.004   015 2
14  Cloud Account   T1087.004   032 2
15  Account Manipulation    T1098   016 1

因此,只有包含云帐户的单元格才会有绿色的背景色


Tags: 代码incloudreturnifmysudoaccount
1条回答
网友
1楼 · 发布于 2024-06-12 02:59:43

如果逻辑更复杂,则可能链接多个条件,例如,此处m1m2用于创建样式的数据框架,如有必要,创建excel文件:

techniques = ['Cloud Account','Account Manipulation']
Fulltechniques = ['Sudo and Sudo Caching']

def my_func_blue(x): 
   c1 = 'background-color: green'
   c2 = 'background-color: red'
   c = ''
   m1 = x.Technique_Name.str.contains('|'.join(techniques))
   m2 = x.Technique_Name.str.contains('|'.join(Fulltechniques))
   m3 = x.Occurance.gt(1)

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1 = df1.mask(m1 & m3, c1).mask(m2, c2)
   return df1

(df.style.apply(my_func_blue,axis=None)
         .to_excel('styled.xlsx', engine='openpyxl', index=False))

相关问题 更多 >