1

I have created a table with sample values. I want the values less than the total average to appear in green and the greater ones in red. So I wrote the following for loop but at least on Jupiter Notebooks I don't see the font changing color

I tried this code:

import pandas as pd
from tabulate import tabulate
from termcolor import colored
from IPython.display import HTML

# Crear un DataFrame de ejemplo
df = pd.DataFrame({
    'Dependencias': ['A', 'B', 'A', 'B', 'C'],
    'tiempo': [10, 20, 30, 40, 50]
})

# Calcular el promedio de tiempo para cada valor de Dependencias
promedio_tiempo_por_dependencias = df.groupby('Dependencias')['tiempo'].mean()

# Calcular el promedio total
promedio_total = promedio_tiempo_por_dependencias.mean()

# Crear una lista de listas para la tabla
tabla = []
tabla.append(['Dependencias', 'Promedio de tiempo'])

# Agregar cada valor promedio a la tabla, resaltando los valores en verde o rojo según si son menores o mayores que el promedio total
for index, value in promedio_tiempo_por_dependencias.items():
    if value < promedio_total:
        valor_coloreado = colored(value, 'green')
    else:
        valor_coloreado = colored(value, 'red')
    tabla.append([index, valor_coloreado])

# Agregar la fila con el promedio total a la tabla, resaltándolo en negrita
tabla.append([colored('Promedio total', 'blue', attrs=['bold']), colored(promedio_total, 'blue', attrs=['bold'])])

# Mostrar la tabla con colores en Jupyter Notebook utilizando HTML
display(HTML(tabla_formateada))
Michel_G
  • 13
  • 2

1 Answers1

0

I don't think you need external libraries to achieve what you want (IIUC).

With , you can broadcast the mean values for each group with GroupBy.transform and then use this :

def color_font(tiempo, target):
    colors = tiempo.gt(target).map({True: "red", False: "green"})
    return [f"color: {font_color}" for font_color in colors]

means = df.groupby("Dependencias")["tiempo"].transform("mean")

stydf = df.style.apply(color_font, target=means, subset=["tiempo"])

Output :

enter image description here

Timeless
  • 22,580
  • 4
  • 12
  • 30