Python Pandas 如果数字等于,则为背景单元格着色
Python Pandas colour background cell if number equals
我目前可以使用以下代码更改单元格的背景:
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 次,它会应用颜色:
东风:
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
因此只有包含云帐户的单元格才会具有绿色背景颜色
如果逻辑更复杂,可以链接多个条件,例如这里 m1
和 m2
用于创建样式数据框,如有必要,创建 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))
我目前可以使用以下代码更改单元格的背景:
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 次,它会应用颜色:
东风:
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
因此只有包含云帐户的单元格才会具有绿色背景颜色
如果逻辑更复杂,可以链接多个条件,例如这里 m1
和 m2
用于创建样式数据框,如有必要,创建 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))