MikeCode
MikeCode

Reputation: 91

Add column when condition match in xlsxwriter

My code is currently highlighting cells when it matches the condition. I need help in figuring out how to append comments in the C column when the cell in either Column A or B is highlighted. I am relatively new to python and xlsxwriter. Any help will be appreciated.

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()

My desired output

    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

Upvotes: 1

Views: 111

Answers (1)

moys
moys

Reputation: 8033

You can do it this way,

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

Output

    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

Upvotes: 1

Related Questions