【问题标题】:Highlighting rows based on a condition根据条件突出显示行
【发布时间】:2021-08-11 22:18:56
【问题描述】:

我有这个包含两列日期的随机数据框,我一直在尝试突出显示条件日期列表中存在开始日期的行。这是我失败的尝试:

import pandas as pd 
import numpy as np
import datetime

df = pd.DataFrame({"Start": pd.date_range("1-jan-2021", periods=10, freq="1H")}).assign(**{"End": lambda d: d["Start"]+pd.Timedelta(hours=20)})

date_condition = ['2021-01-01 05:00:00','2021-01-01 08:00:00', '2021-01-01 02:00:00']
df = df.style.applymap(lambda x: 'background-color : yellow' if x['Start'] in date_condition)

由于我尝试使用 xlswriter 导出此数据框,因此我正在寻找一种即使在 excel 文件中也能保持背景颜色的方法。谢谢!

【问题讨论】:

标签: pandas conditional-formatting xlsxwriter pandas-styles


【解决方案1】:

我们可以使用np.whereSeries.isin 的组合:

date_condition = ['2021-01-01 05:00:00', '2021-01-01 08:00:00',
                  '2021-01-01 02:00:00']

highlighted_rows = np.where(df['Start'].isin(date_condition),
                            'background-color: yellow',
                            '')
# Apply calculated styles to each column:
styler = df.style.apply(lambda _: highlighted_rows)
styler.to_excel('output.xlsx')  # use styler to export to excel
# styler  # to display in NoteBook

或者isin + Series.map:

date_condition = ['2021-01-01 05:00:00', '2021-01-01 08:00:00',
                  '2021-01-01 02:00:00']

highlighted_rows = df['Start'].isin(date_condition).map({
    True: 'background-color: yellow',
    False: ''
})
# Apply calculated styles to each column:
styler = df.style.apply(lambda _: highlighted_rows)
styler.to_excel('output.xlsx')  # use styler to export to excel
# styler  # to display in NoteBook

在 Excel 中:

在 Jupyter 笔记本中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2015-10-30
    • 2020-02-26
    • 1970-01-01
    相关资源
    最近更新 更多