Reputation: 159
In my data set, I want to generate total 180 sheets.
Final=[]
for i in q2:
:
:
Df=pd.concat([SHT_elements,SMT_elements,SLT_elements],axis=0)
Final.append(Df)
from pandas import ExcelWriter
writer = ExcelWriter('datafortrail.xlsx')
Final[0].to_excel(writer, 'sheet1')
Final[1].to_excel(writer, 'sheet2')
Final[2].to_excel(writer, 'sheet3')
:
:
Final[179].to_excel(writer, 'sheet180')
writer.save()
Is there any way for the code to automatically identify the number of sheets to be generate, so I don't need to type Final[].to_excel(writer,'')
180 times?
Upvotes: 0
Views: 116
Reputation: 3306
The line for idx in range(len(df_list))
means : I want the length of my array. Then, using range()
, I will make a list from 0 to the length of my array. And then, with the for loop, we will iterate through the newly created list. Here, in my case, since my list contains 10 dataframes, it'll go from 0 to 9.
I'll access the ten elements of the list using 0 to 9 indexes, and then, using the string format()
method, I'll make a new name for each sheet.
import pandas as pd
from pandas import ExcelWriter
df = pd.DataFrame({
'a' : range(5)
})
df_list = [df.copy() for _ in range(10)] # Making a list of 10 dataframes.
writer = ExcelWriter('some_excel.xlsx')
for idx in range(len(df_list)):
df_list[idx].to_excel(writer, "sheet{}".format(idx+1))
writer.save()
Upvotes: 2