【问题标题】:Highlight cell on condition在条件下突出显示单元格
【发布时间】:2019-09-27 11:43:50
【问题描述】:

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

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

【问题讨论】:

  • 也试过df.style.apply(expired,axis=None)?还要在函数中将df.iterrows() 更改为self.iterrows()(尽管您应该寻找矢量化方式而不是使用 iterrows),但要测试您必须提供数据
  • 没有还是不行
  • 你为什么不尝试提供一个mcve

标签: python pandas jupyter


【解决方案1】:

想法是使用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

【讨论】:

  • rng = pd.date_range('2019-09-25', periods=10) df = pd.DataFrame({'Expiration Date': rng, 'a': range(10)})df.style.apply(expired, axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)
【解决方案2】:

applymap 在每个单元格上执行。如果使用它,您不需要遍历每一行。但是,您似乎正在尝试突出显示整行,因此您可能希望逐行显示apply。使用这种方法,你必须返回一个与每一行大小相同的数组。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多