Home > Blockchain >  Python Pandas: How to change cell font and background color
Python Pandas: How to change cell font and background color

Time:10-07

I want to alter the font and background color of the cell based on the conditions, but my script now just changes the background/cell color. Is there a way I could make the text and cell the same color? I'm not familiar with style.applymap yet so please bear with me.

import pandas as pd
import pypyodbc as odbc

def color(val):
    if  val ==  0:
         color = 'red'
    elif val == 1:
         color = 'green'
    elif val == 3:
         color = 'blue'
    return f'background-color: {color}; color: {color}' 

conn = odbc.connect(MyConn)
rd = pd.read_sql("SELECT * FROM TABLE", conn) 

rdx = pd.pivot_table(rd, index = ['LIST'] ,columns='month',  values='status',aggfunc='sum' )

rdx = rdx.style.applymap(color)

CodePudding user response:

You can mapping values in dictionary if match else return empty string:

df = pd.DataFrame({'a':[2,0,1,3],'b':[3,0,1,3]})
    
def color(val):
    d = {0:'red', 1: 'green', 3:'blue'}
    return f'background-color: {d[val]}; color: {d[val]}' if val in d else ''

df.style.applymap(color)
  • Related