Python 在条件下突出显示单元格

Python 在条件下突出显示单元格,python,pandas,jupyter,Python,Pandas,Jupyter,我试图突出显示当前日期之前的所有单元格。然而,我突出显示的是所有单元格,而不仅仅是旧日期 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_value

我试图突出显示当前日期之前的所有单元格。然而,我突出显示的是所有单元格,而不仅仅是旧日期

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
将熊猫作为pd导入
从日期时间导入日期时间
#获取文件
df=pd.read\u excel(r'C:\Users\cc-621.xlsx')
df
#按日期对数据进行排序
df['Date']=pd.to_datetime(df['Expiration Date'])
df=df.sort_值(按class='Expiration Date')
df=df.reset_index()
df
#按今天日期排序
今天=日期时间。现在(tz=无)
今天
def过期(自我):
对于索引,df.iterrows()中的行:
颜色='red'如果行['Expiration Date']<今天其他行为'green'
返回“背景颜色:%s”%s
new=df.style.applymap(过期)
新的

想法是创建新的数据框,按条件填充样式,使用条件设置行:


applymap
在每个单元格上执行。如果使用此选项,则不需要在每一行上循环。但是,似乎您正试图突出显示整行,因此您可能希望逐行应用
apply
。使用此方法,必须返回与每行大小相同的数组

def expired(val):
    return ['background-color: green' if val['Expiration Date'] else ''] * len(val)

new = df.style.apply(expired, axis=1)

还尝试了
df.style.apply(过期,axis=None)
?也可以将函数中的
df.iterrows()
更改为
self.iterrows()
(尽管您应该寻找一种矢量化的方式,并且不使用iterrows),但要进行测试,您必须提供一个数据。否仍然不起作用为什么不尝试提供一个?
rng=pd.date\u范围('2019-09-25',句点=10)df=pd.DataFrame({'Expiration Date':rng,'a':range(10)})
with
df.style.apply(过期,axis=None)。to_excel('styled.xlsx',engine='openpyxl',index=False)
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
def expired(val):
    return ['background-color: green' if val['Expiration Date'] else ''] * len(val)

new = df.style.apply(expired, axis=1)