Perform operations after styling in a dataframe

Viewed 7975

Whenever I try to perform any operation after styling in my code, I see this error:

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

In this instance I was trying to drop a column after applying a style, in other cases I tried concatenating 2 dataframes, though it throws a similar error. I'm very new to Pandas/Python programming.

For now I have tried to drop before I apply style, that works. But my requirement is to do this AFTER. Likewise I am trying to concatenate AFTER styling which it doesn't allow. I've reduced it to a very simple dataframe

Code:

df = pd.DataFrame([["A", 1],["B", 2]], columns=["Letter", "Number"])
def highlight(s):
    return ['background-color: red']
df = df.style.apply(highlight)
df = df.drop('Number', axis=1)  
with pd.ExcelWriter('testcolor.xlsx') as writer: 
    df.to_excel(writer,sheet_name = 'test')

Error:

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

I expect the column Number to be removed.

1 Answers

When you use style, df becomes a Styler object and it's not anymore a Dataframe object. You are trying to use Dataframe methods on a Styler object, and that will not work. The styler object contains the dataframe inside df.data, so you should do:

df = df.style.apply(highlight)
df.data = df.data.drop('Number', axis=1)     
Related