Reputation: 771
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.
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
Upvotes: 3
Views: 2283
Reputation: 862441
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)
Upvotes: 4