Home > database >  Python Color Dataframe cells depending on values
Python Color Dataframe cells depending on values

Time:05-19

I am trying to color the cells

I have the following Dataframe:

   pd.DataFrame({'Jugador': {1: 'M. Sanchez',
  2: 'L. Ovalle',
  3: 'K. Soto',
  4: 'U. Kanu',
  5: 'K. Abud'},
 'Equipo': {1: 'Houston Dash',
  2: 'Tigres UANL',
  3: 'Guadalajara',
  4: 'Tigres UANL',
  5: 'Cruz Azul'},
 'Edad': {1: 26, 2: 22, 3: 26, 4: 24, 5: 29},
 'Posición específica': {1: 'RAMF, RW',
  2: 'LAMF, LW',
  3: 'RAMF, RW, CF',
  4: 'RAMF, CF, RWF',
  5: 'RW, RAMF, LW'},
 'Minutos jugados': {1: 2053, 2: 3777, 3: 2287, 4: 1508, 5: 1436},
 'Offence': {1: 84, 2: 90, 3: 69, 4: 80, 5: 47},
 'Defense': {1: 50, 2: 36, 3: 64, 4: 42, 5: 86},
 'Passing': {1: 78, 2: 81, 3: 72, 4: 73, 5: 71},
 'Total': {1: 72, 2: 71, 3: 69, 4: 66, 5: 66}})

How can I color the Offence, Defense and Passing cells green if > 60, red < 40 and yellow the rest?

CodePudding user response:

Use Styler.applymap with custom function:

def styler(v):
    if v > 60:
        return 'background-color:green' 
    elif v < 40:
        return 'background-color:red' 
    else:
        return 'background-color:yellow' 
    
df.style.applymap(styler, subset=['Offence','Defense','Passing'])

Alternative solution:

styler = lambda v: 'background-color:green' if v > 60 else 'background-color:red' if v < 40 else 'background-color:yellow'
df.style.applymap(styler, subset=['Offence','Defense','Passing'])

Another approach:

def hightlight(x):
    c1 = 'background-color:green'
    c2 = 'background-color:red'
    c3 = 'background-color:yellow'
    cols = ['Offence','Defense','Passing']

    #DataFrame with same index and columns names as original filled empty strings
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    #modify values of df1 columns by boolean mask
    df1[cols] = np.select([x[cols] > 60, x[cols] < 40], [c1, c2], default=c3)
    return df1

df.style.apply(hightlight, axis=None)
  • Related