I was trying to do the same thing with the question here, and followed the method given by the answers. Here is my code:
import pandas as pd
import xlsxwriter
mylist=[df_1,df_2,df_3]
for n,df in enumerate(mylist):
df=df[df['Name']=='Anna'].copy() # filter each dataframe in the list according to some condition
# print(df)
writer = pd.ExcelWriter('data.xlsx', engine='xlsxwriter')
df.to_excel(writer,'sheet%s' % n)
writer.save()
writer.close()
I was using print(df)
in jupyter notebook to double check if the loop works and each dataframe is successfully filtered, and it does. My problem is, in the output excel file there's only the first filtered data frame df_1
in sheet0
has been saved, the other data frames in the list have not been saved.
What's the problem with my code?