Home > Software engineering >  ValueError when using df.style.apply().to_html()
ValueError when using df.style.apply().to_html()

Time:04-04

I'm having trouble getting my dataframe to HTML when using style.apply().

Using this line of code throws the same error whether I use .render() or .to_html()

df = pd.read_csv(r'C:\test_data.csv')
print(df.style.apply(lambda x: f"color: {'red' if x == 'BAD' else 'black'}", axis=1).to_html())

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

However, when I use .applymap() I can use .to_html() without any errors but I want the condition to be applied row-wise and not element-wise.

CodePudding user response:

When using axis=1 you receive a row and is expected that you return a list with the same length. From documentation:

Parameters: func : function
func should take a Series if axis in [0,1] and return a list-like object of same length, ...

Therefore, you could use a list comprehension for each item in the row:

df.style.apply(lambda row: [f"color: {'red' if i == 'BAD' else 'black'}" for i in row], axis=1).to_html()
  • Related