简体   繁体   English

无法将 DataFrame 列表保存到多表 Excel 电子表格

[英]Failed to save list of DataFrames to multisheet Excel spreadsheet

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.我在 jupyter notebook 中使用print(df)来仔细检查循环是否有效,并且每个 dataframe 都已成功过滤,并且确实有效。 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.我的问题是,在 output excel 文件中,只有sheet0中的第一个过滤数据帧df_1已保存,列表中的其他数据帧尚未保存。

What's the problem with my code?我的代码有什么问题?

You have some pieces inside the loop that should be outside.您在循环内部有一些应该在外部的部分。 Reference the docs here: https://xlsxwriter.readthedocs.io/example_pandas_multiple.html在此处参考文档: 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM