简体   繁体   English

PYTHON Pandas - 基于其他数据帧中的值对数据帧使用 Pandas 样式

[英]PYTHON Pandas - Using Pandas Styling for dataframe based on values in other dataframe

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.我有两个形状相同的数据框。

数据框 1


在此处输入图片说明

在此处输入图片说明

The thing I want to do is, is to color dataframe 1 based on the values contained in dataframe 2.我想要做的是,根据数据帧 2 中包含的值为数据帧 1 着色。

I´m able to color Dataframe 2 based on its own values but I couldn´t manage to transfer the 'Styling' to Dataframe 1.我能够根据自己的值为 Dataframe 2 着色,但我无法将“样式”传输到 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最好的问候,MG

Use applymap with get by dict for DataFrame for colors and pass to Styler.apply :使用applymapget by dict for DataFrame获取颜色并传递给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)

图片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM