Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform operations after styling in a dataframe

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.

like image 265
Rajesh D Avatar asked Jun 18 '19 11:06

Rajesh D


People also ask

How do you apply a style to a data frame?

You can apply conditional formatting, the visual styling of a DataFrame depending on the data within, by using the DataFrame. style property. This is a property that returns a Styler object, which has useful methods for formatting and displaying DataFrames. The styling is accomplished using CSS.

Which operation is supported by Pandas data frame?

One of the essential pieces of NumPy is the ability to perform quick element-wise operations, both with basic arithmetic (addition, subtraction, multiplication, etc.) and with more sophisticated operations (trigonometric functions, exponential and logarithmic functions, etc.).


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)     
like image 117
micric Avatar answered Oct 27 '22 23:10

micric