Home » excel » python – Pandas add cell background color using list and save to excel

python – Pandas add cell background color using list and save to excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have dataframe as below.
enter image description here

I want to change background color by condition and finally I want to save to excel.
There are some cases as follow:

  • condition 1: exact match & case sensitive=False –> red
  • condition 2: contain & case sensitive=False –> yellow
  • condition 3: repeat same character 3 more –> blue

  • list_for_condition1 = [us, ca]

  • list_for_condition1 = [apple, sam]
  • list_for_condition3 = [xxx, xxxx, xxxxxxxxxxx, bbb, aaa]

This is expected output.
enter image description here

I found below code using stype.applymap but couldn’t apply this case.

styled = (df.style.applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else ''))
styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')

How can I solve this?

How to&Answers:

I would define a separate function reflecting your conditions and applymap:

def colorize(x):
    try:
        lower = x.lower()
        # condition 1, pass the corresponding list
        if lower in ['us','ca']: return 'background-color: red'

        # condition 2
        for s in ['apple', 'sam']: 
            if s in lower: return 'background-color: yellow'

        # condition 3
        for s in ['xxx','bbb', 'aaa']:
            if s in lower: return 'background-color:  blue'

        return ''
   except:
        return ''

# toy data
df = pd.DataFrame({'Country':['USA','us','usa','ca', 'CA'],
                   'V1':["Apple", "Applex", 'APPLE', 'SAMSUNG','xxx'],
                   'V2':['Samsung', 'Semsung', 'SamSung1', 'apple', 'bbbb'],
                   'V3':['SAMSUNG', 'SS','APPLEXX', 'APPLEs', 'aaa']
                   })

df.style.applymap(colorize)

Output:

enter image description here