1

I created a loop with a dataframe variable. At every round in the loop I'd like to have the dataframe written to a different tab in the same excel file. However, it seems like because the dataframes are assigned to the same variable name, overwriting on the same tab happens. So in the end, instead of having 7 tabs accommodating 7 tables (dataframes), I end up having only one tab in the excel file carrying the last dataframe in the loop. See below. If my explanation is not clear, please let me know.

Is there a way to fix this? Or any alternative way to do this properly? Thanks for your kind help.

for i in range(7):
        #some codes to manipulate dataframe converted_df
        with pd.ExcelWriter(r'path') as writer:  
                converted_df.to_excel(writer, sheet_name = "{}".format(spec[i]))

1 Answer 1

1

You can try change order of code:

with pd.ExcelWriter(r'path') as writer: 
    for i in range(7):
        #some codes to manipulate dataframe converted_df
        converted_df.to_excel(writer, sheet_name = "{}".format(spec[i]))
                
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.