For Loop to Write Multiple Dataframes to Separate Excel Sheets

Question:

I’ve been trying to figure out where my code is going wrong but I can’t seem to figure out the error. The goal of this code snippet is pretty simple. I read in my CSV into a data frame and create a list of the unique subfunctions in the Sub Function1 column. My goal is to create an excel workbook with separate worksheets for each of the unique subfunctions, filtered by the respective subfunction. Can anyone help point me in the right direction/let me know where I’m going wrong? Thanks
`

import pandas as pd

fileName = 'Hierarchy_Filtered.csv'
filterField = 'Sub Function1'

df = pd.read_csv(fileName)
finance_subfunctions = df[filterField].unique()

data_fields = ['Employee ID', 'Employee First Name', 'Employee Last Name', 'Hire Date', 'Work Location Code Desc', 'Dept Description', 'Job Profile Name']

writer = pd.ExcelWriter('output.xlsx')

for subfunction in finance_subfunctions:
    df2 = df.loc[df[filterField] == subfunction]
    df2 = df2[data_fields]
    df2.to_excel(writer, sheet_name=subfunction, index=False)

`

I was expecting this to work, however when I run it, nothing happens.

Asked By: Andrew Puetz

||

Answers:

you need to add writer.save() at the end of your codes so that it will close the Excel writer and output the Excel file

Answered By: qthu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.