Skip to content
Advertisement

Mutiple style for one DataFrame issues

I would like to understand how “style” works in python, I always have the same error : AttributeError: ‘Styler’ object has no attribute ….

df_x = team_table()

df_x1 = df_x[1:].style.applymap(lambda x: f"background-color: {'#28D1C5' if x > 2 else ''}")
        .applymap(lambda x: f"background-color: {'#FFC33C' if x < -2 else ''}")
        .format(precision=2)  

df_x0 = df_x.style.apply(lambda x: x.index.map({"Participants":'background-color: #FFFFA7'}))
            .format(precision=2)

for now, I manage to have :

  • the first row in yellow but not the conditional formatting (df_x0)

  • and the conditional formatting blue and orange cells but the first row disappear because I am obligate to apply style on df_x[1:] otherwise I have TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’. (df_x1)

The result I want:

result I want

Advertisement

Answer

You could check if the value is a number: if not make a yellow background, otherwise apply colors as usual:

import pandas as pd
import numpy as np
import numbers

np.random.seed(0)
df = (pd.DataFrame([list('abcdef')] + ((np.random.rand(5,6) - 0.5) * 10).tolist()))

df.style.applymap(lambda x: 
    f"background-color: {'#FFFFA7' if not isinstance(x, numbers.Number) else '#28D1C5' if x > 2 else '#FFC33C' if x < -2 else 'white'}"
    ).format(precision=2) 

enter image description here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement