【问题标题】:PYTHON Pandas - Using Pandas Styling for dataframe based on values in other dataframePYTHON Pandas - 根据其他数据帧中的值对数据帧使用 Pandas 样式
【发布时间】:2019-07-14 01:51:00
【问题描述】:

我已经处理这个挑战很长一段时间了,但我想不出一个像样的解决方案。

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


我想做的是,根据数据框 2 中包含的值对数据框 1 进行着色。

我可以根据 Dataframe 2 自己的值为其着色,但我无法将“样式”转移到 Dataframe 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)

谁能指导我完成这个? :-)

非常感谢!

最好的问候, MG

【问题讨论】:

    标签: python pandas dataframe styles highlight


    【解决方案1】:

    使用applymapget by 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)
    

    【讨论】:

    • 你太棒了!这对我有用!我只剩下一个问题:如何处理此错误/警告?:Python36_64\lib\site-packages\pandas\io\formats\excel.py:312: CSSWarning: Unhandled color format: '' Happens for the cells with没有值,我猜在这种情况下''
    • @mgruber - 你的熊猫版本是什么?
    • @mgruber - 很奇怪,对我来说它工作得很好,可以升级到最新版本吗?
    • @mgruber - 如何将colors.get(val,'') 更改为colors.get(val,None)
    • @jezreal Brilliant!
    猜你喜欢
    • 2017-12-19
    • 2022-07-06
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2020-09-20
    • 1970-01-01
    相关资源
    最近更新 更多