Étienne
Étienne

Reputation: 13

writing a pandas dataframe variable to excel

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

Upvotes: 1

Views: 159

Answers (1)

jezrael
jezrael

Reputation: 863791

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

Upvotes: 1

Related Questions