python - xlsxwriter 中条件匹配时添加列

标签 python pandas xlsxwriter

我的代码当前在匹配条件时突出显示单元格。当 A 列或 B 列中的单元格突出显示时,我需要帮助弄清楚如何在 C 列中附加注释。我对 python 和 xlsxwriter 比较陌生。任何帮助将不胜感激。

import numpy as np
import pandas as pd

df = pd.DataFrame({"ID": [10, 11, 12, 13, 14], 
"Status": ['item1', 'item2', 'item3', 'item4', 'item5']})



number_rows = len(df.index) + 1
writer = pd.ExcelWriter("Report.xlsx",engine='xlsxwriter')

df.to_excel(writer, sheet_name='Sheet1', index=False)

workbook = writer.book
worksheet = writer.sheets['Sheet1']



format1 = workbook.add_format({'bg_color': '#FFC7CE',
                              'font_color': '#9C0006'})

format2 = workbook.add_format({'bg_color': '#FFFF00',
                              'font_color': '#9C0006'})



a1=[10,12,14]
for a in a1:
    worksheet.conditional_format("$A$1:$A$%d" % (number_rows),
                                     {"type": "cell",
                                      'criteria': '=',
                                      "value": a,
                                      "format": format1
                                     })

stat= ['item1', 'item2']
for b in stat:
    worksheet.conditional_format("$B$1:$B$%d" % (number_rows),
                                     {"type": "text",
                                      'criteria': 'containing',
                                      "value": b,
                                      "format": format2
                                     })

workbook.close()

我想要的输出

    A   B        C
    10  item1    10 and item1 both highlighted
    11  item2    item2 was highlighted
    12  item3    12 was highlighted
    13  item4
    14  item5    14 was highlighted

最佳答案

你可以这样做,

a1=[10,12,14]
stat= ['item1', 'item2']
df['C'] =df.apply(lambda x: ''.join([str(a)+' was highlighted' for a in a1 if x.ID==a]) or ''.join([sta +' was highlighted' for sta in stat if x.Status==sta]),axis=1) 
df

输出

    ID  Status  C
0   10  item1   10 was highlighted
1   11  item2   item2 was highlighted
2   12  item3   12 was highlighted
3   13  item4   
4   14  item5   14 was highlighted

关于python - xlsxwriter 中条件匹配时添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106601/

相关文章:

python - 我收到预期错误 <class 'openpyxl.styles.fills.Fill' > 使用 pandas read_excel 读取 excel 文件

python - 如何避免使用 python 覆盖 excel 中的单元格?

python - 使用索引和值过滤 Pandas 系列

python - 如何将 StringTemplate 引擎集成到 CherryPy Web 服务器中

python - Pandas 创建复制另一个单元格值的列

python - 如何从 for 循环构建和填充 Pandas 数据框?

python - 值错误 : Series lengths must match to compare when matching dates in Pandas

python - XlsxWriter 中出现意外的单元格格式化行为

python - 使用 Python 应用 Excel 公式创建新的数据框列

python - 更新 Python Pickle 对象