Search code examples
pythonpandasdataframe

AttributeError: 'Styler' object has no attribute 'style'


This is my DataFrame:

import pandas as pd
df = pd.DataFrame(
    {
        'a': [2, 2, 2, -4, 4, 4, 4, -3, 2, -2, -6],
        'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6]
    }
)

I use a function to highlight cells in a when I use to_excel:

def highlight_cells(s):
    if s.name=='a':
        conds = [s > 0, s < 0, s == 0]
        labels = ['background-color: lime', 'background-color: pink', 'background-color: gold']
        array = np.select(conds, labels, default='')
        return array

    else:
        return ['']*s.shape[0]

Now I want to add one more feature by adding plus sign if a value in a is positive. For example 1 becomes +1. I want this feauture only for column a.

This is my attempt but it does not work. It gives me the error that is the title of the post.

df.style.apply(highlight_cells).style.format({'a': '{:+g}'}).to_excel('df.xlsx', sheet_name='xx', index=False)

Solution

  • style.apply already returns a Styler object, you only need further do operation on this, i.e.

    df.style.apply(highlight_cells).format(...)
    #                               ^
    #                               |
    #                               No need .style again