在xlsxwriter中为熊猫条件格式传递变量

问题描述 投票:0回答:1

我正在数据帧中运行for循环,只要它符合特定条件,我想在输出报告中突出显示该行。但是,我的代码适用于硬编码的值(即10),但是我想传递一个变量。任何帮助表示赞赏。

df = pd.DataFrame({"ID": [10, 11, 12, 13, 14], 
"NAME": ['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']


a = df['ID'][1]

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

worksheet.conditional_format("$A$1:$B$%d" % (number_rows),
                             {"type": "formula",
                              "criteria": '=INDIRECT("A"&ROW())= 10',  # I want to pass variable (a) instead of '10'
                              "format": format1
                             }
)
workbook.close()
python pandas xlsxwriter
1个回答
0
投票

找到了一种使用“值”属性添加变量的方法

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'})

worksheet.conditional_format("$A$1:$B$%d" % (number_rows),
                             {"type": "cell",
                              'criteria': '=',
                              "value": a,           #here a is variable now
                              "format": format1
                             }
)
workbook.close()
© www.soinside.com 2019 - 2024. All rights reserved.