Styler object has no attribute style
Asked Answered
T

3

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

Tillio answered 7/6, 2021 at 9:21 Comment(1)
This answer addresses the approaches to applying multiple styles to the same DataFrame.Interface
L
4

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.

Lindberg answered 7/6, 2021 at 9:36 Comment(1)
Applying all filters with single apply is not possible as filters are different for different colsTillio
H
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;"')
Haye answered 11/10, 2021 at 18:20 Comment(0)
F
0

The below approach works for me. As the df.style returns styler object, you just use this object to apply different style. Every time you can df.style, it returns a new styler object, so you cannot use multiple df.style

    # this line is the key point
    df_style = df.style
    xxxxxxx
    df_style.map(mark_color, subset_status, color='yellow')
    xxxxx
    df_style.map(mark_color, subset_studentid, color='green')
    xxxxx
    # save the style and output the excel, note that use the df_style instead of the df
    df_style.to_excel(writer, index=False, engine="openpyxl", sheet_name='Details')
    

Floruit answered 31/10 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.