I am using df.to_excel()
to output data from a pandas dataframe to excel. To improve readability, I am using df.style.applymap()
to change the color of the cell based on the contents.
Imagine I have a dataframe that looks like:
df =
Account Revenue AccountAge
0 "Boeing" 5000 5.6
1 "Lockheed" -10000 1.2
2 "Airbus" 12000 0.6
3 "Northrop" -3000 8.4
Where account age represents how long I have had this account on my books. Perhaps I want to flag negative revenue cells as red. I can do:
def color_neg_revenue(val):
if val < 0:
color = 'red'
return "background-color: %s" % color
df = df.style.applymap(color_neg_revenue, subset=["Revenue"])
I can export this to excel, and the format looks great! But suppose I also want to flag new accounts in yellow, when I try:
def color_new_account(val):
if val < 3:
color = 'yellow'
return "background-color: %s" % color
df = df.style.applymap(color_new_account, subset=["AccountAge"])
I get:
AttributeError: 'Styler' object has no attribute 'style'
Why can I not use applymap()
on a dataframe that I have already used applymap()
on? How can I get around this?