How do I nest these for loops in Pandas Xlsx writer

Viewed 36

I am new to Python/Pandas and I am stuck on this issue.

I have 2 excel sheets, 'Sheet1' and 'Sheet2', which are created from 2 separate dataframes 'df1' and 'df2'.

I am currently using for loops to highlight a specified list of columns in each sheet into 3 different colors - green, blue, and gray. Each sheet has different column names that need to be highlighted thus why I am using for loops.

However, the for loops are slowing down the runtime significantly so I am wondering, how do I merge these for loops in Pandas Xlsx writer?

df1.to_excel(writer,sheet_name='Sheet1', startrow=1, header=False, index=False)
df2.to_excel(writer,sheet_name='Sheet2', startrow=1, header=False, index=False)
sheet1ws = writer.sheets['Sheet1']

for col_num, col_name in enumerate (df1.columns.values):
    if col_name in columns_to_highlight_green:
        sheet1ws.write(0, col_num, col_name, green_fmt)
    elif col_name in columns_to_highlight_blue:
         sheet1ws.write(0, col_num, col_name, blue_fmt)
    elif col_name in columns_to_highlight_gray:
         sheet1ws.write(0, col_num, col_name, gray_fmt)
    else:
        sheet1ws.write(0, col_num, col_name, general_fmt)
sheet2ws = writer.sheets['Sheet2']

for col_num, col_name in enumerate (df2.columns.values):
    if col_name in columns_to_highlight_green:
        sheet2ws.write(0, col_num, col_name, green_fmt)
    elif col_name in columns_to_highlight_blue:
         sheet2ws.write(0, col_num, col_name, blue_fmt)
    elif col_name in columns_to_highlight_gray:
         sheet2ws.write(0, col_num, col_name, gray_fmt)
    else:
        sheet2ws.write(0, col_num, col_name, general_fmt)
0 Answers
Related