我正在尝试突出显示当前日期之前的所有单元格。但是,我要突出显示所有单元,而不只是旧日期。
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
答案 0 :(得分:2)
想法是使用Styler.apply
创建按条件填充样式的新DataFrame,用于按条件设置行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
:
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
答案 1 :(得分:2)
VUE Component
在每个单元格上执行。如果使用此方法,则不需要遍历每一行。但是,您似乎正在尝试突出显示整行,因此您可能希望逐行applymap
。使用此方法,您必须返回一个与每一行相同大小的数组。
apply