How to save each dataframe produced by a for loop to the same excel sheet, but different sheets?

Question:

I’m writing python script (in jupyter notebook, using pandas and numpy) where I have a for loop that produces a single matrix each iteration, in this for loop i want each matrix to be saved to an excel file, each iteration matrix should be saved to its own sheet in the excel file before the for loop goes to the next iteration. I’d like the matrix from the 1st iteration to be saved in Sheet 1, matrix from 2nd iteration in Sheet 2,… matrix from nth iteration in Sheet n.

Below is what i have as of now, but this just rewrites each iteration matrix into the same single excel sheet. I am new to staockoverflow (and python) so not sure if i formatted my example script correctly, sorry.

> for r in range (10):
>     Matrix = np.empty((1000,317))
>     for i in range(1000):
>         for j in range (317):
>             if-else statements that fill out Matrix
> 
>     PP = pd.DataFrame(Matrix) 
>     PP.to_excel('File.xlsx', sheet_name='Sheet{}'.format(r+1), header=False, index=False)
Asked By: suyinar

||

Answers:

Please see the pandas ExcelWriter docs and the following example found there:

df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"])  
df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])  
with pd.ExcelWriter("path_to_file.xlsx") as writer:
    df1.to_excel(writer, sheet_name="Sheet1")  
    df2.to_excel(writer, sheet_name="Sheet2") 
Answered By: constantstranger

I have removed two inner for loops for the performance, try this solution:

!pip install openpyxl
import pandas as pd
import numpy as np

writer = pd.ExcelWriter('example.xlsx', engine='openpyxl')
for r in range(3):
    Matrix = np.ones((1000,317))
    df = pd.DataFrame(Matrix)
    df.to_excel(writer, sheet_name=f'{r+1}', header=False, index=False)
writer.save()

enter image description here

Answered By: Sergey Sakharovskiy