1

I have a dataframe with several columns and a list with colors associated with each column. I want to highlight the non-blank cells in each column with the associated color.

I've tried iterating over the columns in various ways. The closest thing to success was to put a for loop in the styling function and apply it within a for loop. This correctly highlights the last column, but not the rest.

df=pd.DataFrame({'a':[1,2,3,4],'b':['','',1,''],'c':['a','b','c','']})
df_column_colors=['red','blue','green']

def highlight_cells(value):
    if value=='':
        background_color=None
    else:
        for v in range(len(df_column_colors)):
            background_color=str(df_column_colors[v])
    return 'background-color: %s' % background_color
for i in range(len(df.columns)):
     df2=df.style.applymap(highlight_cells,subset=df.columns[i])
2
  • What is time.columns? Commented Jul 19, 2019 at 17:16
  • A bit of the actual code that I missed in making it generic. I've edited the function in the question and the results are the same. Commented Jul 19, 2019 at 17:25

2 Answers 2

0

you can do this as below:

d= dict(zip(df.columns,['background-color:'+i for i in df_column_colors]))
#{'a': 'background-color:red', 'b': 'background-color:blue', 'c': 'background-color:green'}
def mycolor(x):
    s=pd.DataFrame(d,index=x.index,columns=x.columns)
    df1=x.mask(x.replace('',np.nan).notna(),s)
    return df1
df.style.apply(mycolor,axis=None)

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly, and was much cleaner than my attempt. Thanks!
0

Try this:

df = pd.DataFrame({'a':[1,2,3,4],'b':['','',1,''],'c':['a','b','c','']})
df_column_colors=['red','blue','green']

def apply_color(cells):
    color = df_column_colors[df.columns.get_loc(cells.name)]
    colors = []
    for cell in cells:
        if cell == '':
            colors.append('')
        else:
            colors.append('background-color: %s' % color)
    return colors

df.style.apply(apply_color)

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.