5

This is a follow up question on applying background color to a dataframe based on condition

I am able to apply style based on the below:

f = lambda v: 'background-color: %s' % 'green' if v=='col' else ''
df = df.style.applymap(f, subset=['a'])

My challenge now is I want to do more filters on different cols. So If I try to apply this style.applymap on df again I get the error mentioned in title. Because it can be applied on DF and not styler object.

As a workaround I found to use df.data.style.applymap to a styled object but then it is not retaining the previous style.

I have multiple filter conditions that may involve same columns for which style is already applied.

How can I apply multiple styles one after other ? Checked the documentation but didnt find anything

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
EXODIA
  • 908
  • 3
  • 10
  • 28
  • [This answer](https://stackoverflow.com/a/68688830/15497888) addresses the approaches to applying multiple styles to the same DataFrame. – Henry Ecker Sep 06 '21 at 00:37

2 Answers2

3

Applying style on a dataframe returns a Styler object, not a DataFrame. You cannot apply further style operations on that.

What you can do is to apply all your styling operations with a single apply/applymap.

If that is too complex, a not too nice hack is to create new columns to make all your styling possible and then hide these columns with the style operation.

nocibambi
  • 2,065
  • 1
  • 16
  • 22
  • Applying all filters with single apply is not possible as filters are different for different cols – EXODIA Jun 07 '21 at 09:58
2
f = lambda v: 'background-color: %s' % 'green' if v=='col' else ''
df = df.style.applymap(f, subset=['a'])

if you use single style means above code will work fine. If you using multiple style means remove that style.

def format_color_groups(values):
    if values =='Y':
        return  'color:red;border-collapse: collapse; border: 1px solid black;'
    elif values  == 'N':
        return  'color:green;border-collapse: collapse; border: 1px solid black;'
    else:
        return  'border-collapse: collapse; border: 1px solid black;'

df = df.style.applymap(format_color_groups)
#now df is styler so no need to add style
df = df.set_table_attributes('style="border-collapse: collapse; border: 1px solid black;"')
Tyler2P
  • 2,324
  • 26
  • 22
  • 31