突出显示条件中的单元格 [英] Highlight cell on condition

查看:62
本文介绍了突出显示条件中的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示当前日期之前的所有单元格.但是,我突出显示了所有单元格,而不只是旧的日期.

I'm trying to highlight all cells that are before the current date. However I am highlighting all cells instead of just the old dates.

import pandas as pd
from datetime import datetime 

#get file 
df = pd.read_excel(r'C:\Users\cc-621.xlsx')
df

# sort the data by date 
df['Date'] = pd.to_datetime(df['Expiration Date'])
df = df.sort_values(by='Expiration Date')
df = df.reset_index()
df

# sort by todays date 
today = datetime.now(tz=None)
today

def expired(self):
    for index, rows in df.iterrows():
        color = 'red' if rows['Expiration Date'] < today else 'green'
        return 'background-color: %s' %color

new = df.style.applymap(expired)
new

推荐答案

想法是使用

Idea is create new DataFrame filled by styles by condition with Styler.apply, for set rows by conditions is used numpy.where:

def expired(x):
    c1 = 'background-color: red'
    c2 = 'background-color: green'

    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    m = x['Expiration Date'] < today
    df1['Expiration Date'] = np.where(m, c1, c2)
    return df1

df.style.apply(expired, axis=None)

如果按条件为所有行着色,请使用 DataFrame.mask :

If coloring all rows by condition use DataFrame.mask:

def expired(x):
    c1 = 'background-color: red'
    c2 = 'background-color: green'

    df1 = pd.DataFrame(c1, index=x.index, columns=x.columns)
    m = x['Expiration Date'] < today
    df1 = df1.mask(m, c2)
    return df1

这篇关于突出显示条件中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆