1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

AttributeError: 'int' object has no attribute 'lower'
I saw that coming. See update with try:.. except:.
error occurred ( 'int' object has no attribute 'lower') and 'CA' in Country Column not change background color.
For reference, you did say case sensitive, which means 'ca' != 'CA'. Anyway, see update.
sorry, my mistake. I means case sensitive=False. Thank you for your inform.

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.