3

I´m dealing with this challenge quite a while and I couldn´t come up with a decent solution.

I have two dataframes with the same shape.

Dataframe 1


enter image description here

enter image description here

The thing I want to do is, is to color dataframe 1 based on the values contained in dataframe 2.

I´m able to color Dataframe 2 based on its own values but I couldn´t manage to transfer the 'Styling' to Dataframe 1.

Here is my code for this:

df1 = ...
df2 = ...

def apply_color(val):

    colors = {1: 'green',2: 'blue', 3: 'yellow', 4: 'orange', 5: 'grey'}

    return 'background-color: {}'.format(colors[val]) if val else ''

df2.style.applymap(df2)

Can anyone guide me to finalize this? :-)

Thanks a lot!

Best Regards, MG

1 Answer 1

4

Use applymap with get by dict for DataFrame for colors and pass to Styler.apply:

df1 = pd.DataFrame({
         'B':[4,5,4],
         'C':[7,8,9],
         'D':[1,3,5],


})

df2 = pd.DataFrame({
         'B':[1,np.nan,4],
         'C':[np.nan,2,np.nan],
         'D':[1,3,np.nan],

})

def apply_color(x):
    colors = {1: 'green',2: 'blue', 3: 'yellow', 4: 'orange', 5: 'grey'}
    return df2.applymap(lambda val: 'background-color: {}'.format(colors.get(val,'')))

df1.style.apply(apply_color, axis=None)

pic

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

10 Comments

You are awesome! This works for me! I only got one question left: How do I handle this error / warning?: Python36_64\lib\site-packages\pandas\io\formats\excel.py:312: CSSWarning: Unhandled color format: '' Happens for the cells with no values, i guess in this case ''
@mgruber - What is your pandas version?
@mgruber - It is weird, for me it working nice, is possible upgade to last version?
@mgruber - How working change colors.get(val,'') to colors.get(val,None) ?
@jezreal Brilliant!
|

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.