Styler object has no attribute style

Viewed 8144

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

2 Answers

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.

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;"')
Related