I'm trying to apply a styler function to a df but getting this error and I don't know how to fix it.
ValueError: Function <function highlight at 0x0000029D89935F30> resulted in the apply method collapsing to a Series.
Usually, this is the result of the function returning a single value, instead of list-like.
I have a dataframe like below
Value Limit Actual
Issues < 33 0
Rating > 4 4.2
Complaints < 15 18
Time 30 - 45 41
Tip -- -
I want to color the column Actual based on the Limit column.
For example if the
Limithas "< 33", I want to colorActualas Green if the value inActualcolumn is less than 30, if not Red. Similarly for other rows as well.If the
Limithas "30-45", I want to colorActualas Green if the value inActualcolumn is between 30 & 45 , if not Red.If the
Limithas "-", I want to colorActualas Yellow.
Based on this SO question Link, I created a function that evaluates the logic.
import re
def highlight(row):
numbers = re.findall('[0-9]+', row['Limit'])
if row['Value'] in ('Issues','Rating','Complaints'):
if '>' in row['Limit'] and row['Actual'] > numbers[0]:
color = 'green'
elif row['Actual'] < numbers[0]:
color = 'green'
else:
color = 'red'
else:
if len(numbers) == 0:
color = 'yellow'
elif row['Actual'] > numbers[0] and row['Actual'] < numbers[1]:
color = 'green'
else:
color = 'red'
return f"background-color: {color}"
However, when I try df.style.apply(highlight, axis=1), I get the error message at the beginning of the question.
How do I properly implement my logic to get the coloring I want? Below is what I want when I export this df to excel.
