熊猫DataFrame列的条件格式设置(单元格突出显示)

时间:2020-06-05 10:23:02

标签: python-3.x pandas conditional-formatting

我制作了一个脚本,用于每日数据趋势分析,同样,如果它与前一天的值有偏差,我想按颜色突出显示单元格的值。列标题将根据日期而变化。因此,我正在使用列索引来定位它。

我是条件格式的新手,并且没有太多深入的想法。 我的努力在下面,但是我遇到了错误。 我的数据框如下所示:

enter image description here

代码:

import pandas as pd

def highlight_greater(x):
    r = 'red'
    g = 'gray'

    m1 = df1[df1.columns[(-2)]] > df1[df1.columns[(-4)]]
    m2 = df1[df1.columns[(-2)]] < df1[df1.columns[(-4)]]

    df1 = pd.DataFrame('background-color: ', index=df1.index, columns=df1.columns)

    df1[df1.columns[(-2)]] = np.where(m1, 'background-color: {}'.format(r), df1[df1.columns[(-2)]])
    df1[df1.columns[(-2)]] = np.where(m2, 'background-color: {}'.format(g), df1[df1.columns[(-2)]])
    return df1


dfstyled = dfnew.style.apply(highlight_greater,subset[dfnew[dfnew.columns[-2]]],axis=1)

dfstyled.to_excel("C:\\Users\\mine\\styled.xlsx",engine='openpyxl')

所需输出: enter image description here

0 个答案:

没有答案