【问题标题】:How to make comparison dependent on conditions on the dataframe columns?如何根据数据框列的条件进行比较?
【发布时间】:2019-10-17 14:28:10
【问题描述】:

我想用这样的一些条件逐个单元格地突出显示:

df = pd.DataFrame(...)

def highlight(row):

    if row[0] > row[1]:
        color = 'red'

    elif row[0] < row[1]:
        color = 'green'

    else:
        color = 'yellow'

    background = ['background-color: {}'.format(color) for row in df['col1']]
    return background


df2 = df.style.apply(highlight, axis = 1)
df2.to_excel('style.xlsx')

顺便说一下,我想在 col1 和 col2 之间进行比较。

我在等你的帮助。

【问题讨论】:

    标签: pandas styling


    【解决方案1】:

    不返回列的背景,而是返回行:

    np.random.seed(1)
    df = pd.DataFrame(np.random.randint(0,3, (10,4)),
                      columns=('hour','col1','col2','col3'))
    
    def highlight(row):
        if row['col1'] > row['col2']:
            color='red'
        elif row['col1'] < row['col2']:
            color='green'
        else: color = 'yellow'
    
        # notice the difference
        # also color:black is not needed, just add because my jupyter style
        background=['',f'background-color:{color}; color:black','','']
        return background
    
    df.style.apply(highlight,axis=1)
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2018-07-25
      • 2020-11-25
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多