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.
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.
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.).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With