1

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

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

I've changed it for my variables but it appears to stop after the first match where I would need it to work its way through it all. E.G out of my list above only "Sudo and Sudo Caching" is matching as RED and thats all
@TiiTcHY - Can you check now? I change isin for Series.str.contains for match all values of lists joined by | for regex or

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.