如何将DataFrames列表导出到一个Excel电子表格中?状态 文档to_excel:
to_excel
注意 如果传递现有的ExcelWriter对象,则工作表将添加到现有的工作簿中。这可用于将不同的DataFrame保存到一个工作簿中 writer = ExcelWriter('output.xlsx') df1.to_excel(writer, 'sheet1') df2.to_excel(writer, 'sheet2') writer.save()
注意 如果传递现有的ExcelWriter对象,则工作表将添加到现有的工作簿中。这可用于将不同的DataFrame保存到一个工作簿中
writer = ExcelWriter('output.xlsx') df1.to_excel(writer, 'sheet1') df2.to_excel(writer, 'sheet2') writer.save()
writer = ExcelWriter('output.xlsx')
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save()
之后,我想我可以编写一个将DataFrame列表保存到一个电子表格的函数,如下所示:
from openpyxl.writer.excel import ExcelWriter def save_xls(list_dfs, xls_path): writer = ExcelWriter(xls_path) for n, df in enumerate(list_dfs): df.to_excel(writer,'sheet%s' % n) writer.save()
但是(带有两个小DataFrame的列表,每个小DataFrame可以to_excel单独保存),引发了一个异常 (编辑:删除了traceback) :
AttributeError: 'str' object has no attribute 'worksheets'
大概我ExcelWriter打错电话了,应该怎么做才能做到这一点?
ExcelWriter
您应该使用熊猫自己的ExcelWriter课程:
from pandas import ExcelWriter # from pandas.io.parsers import ExcelWriter
然后该save_xls函数将按预期工作:
save_xls
def save_xls(list_dfs, xls_path): with ExcelWriter(xls_path) as writer: for n, df in enumerate(list_dfs): df.to_excel(writer,'sheet%s' % n) writer.save()