1

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?

Anthony
  • 43
  • 4

1 Answers1

1

You have some pieces inside the loop that should be outside. Reference the docs here: https://xlsxwriter.readthedocs.io/example_pandas_multiple.html

writer = pd.ExcelWriter('data.xlsx', engine='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) 
    df.to_excel(writer,'sheet%s' % n)
writer.save()
Jonathan Leon
  • 5,440
  • 2
  • 6
  • 14