Py学习  »  Python

python pandas-基于其他dataframe中的值对dataframe使用pandas样式

mgruber • 7 年前 • 2477 次点击  

我处理这个挑战已经有一段时间了,我想不出一个像样的解决办法。

我有两个形状相同的数据帧。

Dataframe 1


enter image description here

enter image description here

我要做的是,根据dataframe 2中包含的值给dataframe 1上色。

我可以根据数据框2本身的值给它上色,但是我无法将“样式”转换成数据框1。

这是我的代码:

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)

有人能指导我完成这件事吗?-)

谢谢!

谨致问候, 镁

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44203
文章 [ 1 ]  |  最新文章 7 年前
jezrael
Reply   •   1 楼
jezrael    7 年前

使用 applymap 具有 get 通过DICT 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)

pic