5

I have one pandas dataframe that I want to style the format based on the values of another dataframe of the same shape/size. I'm trying to use applymap.

Here's an example:

t1= pd.DataFrame({'x':['A','B','C'], 'y':['C','B','D']})
t2= pd.DataFrame({'x':[0.3,0.2,0.7], 'y':[1,0.3,2]})

def color_cells(s, threshold=0.5):
    if s > threshold:
        return 'color:{0}; font-weight:bold'.format('red')
    else:
        return ''

#Tried
t1.style.applymap(t2.applymap(color_cells))

Ideally in t1 where the corresponding cells in t2>0.5 then the values in t1 are in 'red-bold'.

However, I'm unsure what pattern I should use to get this desired effect.

1 Answer 1

10

You were almost there, you need to use the apply function with a lambda instead to iterate through the cells.

t1.style.apply(lambda x: t2.applymap(color_cells), axis=None)

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

1 Comment

Can anyone explain how the above code works? It looks like for each item in t1, apply color_cells only to the corresponding item in t2 that has the same (x,y) location as the item in t1. But the code reads more like this to me—applying color_cells to every item in t2 for each item in t1. Where can I find documentation that clarifies the behavior of applymap/map with an outer apply?

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.