TiiTcHY
TiiTcHY

Reputation: 69

Python Pandas colour background cell if number equals

I am currently able to change the background of a cell using the following code:

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

I want to be able to add another IF statement into

"if val in techniques" 

so if the occurrence is MORE THAN 1 it applies the colour:

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

So only the cell which contains Cloud Account would have the background colour of Green

Upvotes: 1

Views: 431

Answers (1)

jezrael
jezrael

Reputation: 863331

If logic is more complicated is possible chain multiple conditions, e.g. here m1 with m2 for create Dataframe of styles and if necessary create excel file:

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

Upvotes: 1

Related Questions