0

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)
4
  • @jezrael, Thanks for the reply ..good Question.. the reason is that I want to hide the text.. the color is only visible .. I used the text for the Total ... the values in the status are 0,1,2 and 3 Commented Oct 7, 2022 at 8:22
  • @jezrael, does not changed the Font Color only the background. return f'background-color: {bgcolor}; colors: {bgcolor} Commented Oct 7, 2022 at 8:26
  • 1
    there was typo, color instead colors. Commented Oct 7, 2022 at 8:36
  • There is problem if no match, so added anothe solution Commented Oct 7, 2022 at 9:00

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.