美文网首页
DataFrame写入excel不同的sheet

DataFrame写入excel不同的sheet

作者: okcdev | 来源:发表于2019-04-11 16:47 被阅读0次

直接上代码

初始化2个dataframe
df1 = pd.DataFrame(
    {
        'Name':['Jack', 'Kate', 'Jim', 'Steve'],
        'Gender':['M','F','M','M'],
        'Height':[17,15, 22, 18]
    }
)

df2 = pd.DataFrame(
    {
        'Name':['Jack', 'Kate', 'Jim', 'Steve'],
        'Gender':['M','F','M','M'],
        'Height':[17,15, 22, 18]
    }
)
准备输出写文件
write = pd.ExcelWriter('./output.xls')
df1.to_excel(excel_writer=write,sheet_name='df1_sheet', header=True, encoding="utf-8", index=False)
df2.to_excel(excel_writer=write,sheet_name='df2_sheet', columns=['Name', 'Gender'], header=True, encoding="utf-8", index=False)
write.save()
write.close()
执行结果
image.png
image.png
to_excel部分源码
    def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
                 float_format=None, columns=None, header=True, index=True,
                 index_label=None, startrow=0, startcol=0, engine=None,
                 merge_cells=True, encoding=None, inf_rep='inf', verbose=True,
                 freeze_panes=None):

        from pandas.io.formats.excel import ExcelFormatter
        formatter = ExcelFormatter(self, na_rep=na_rep, cols=columns,
                                   header=header,
                                   float_format=float_format, index=index,
                                   index_label=index_label,
                                   merge_cells=merge_cells,
                                   inf_rep=inf_rep)
        formatter.write(excel_writer, sheet_name=sheet_name, startrow=startrow,
                        startcol=startcol, freeze_panes=freeze_panes,
                        engine=engine)

相关文章

网友评论

      本文标题:DataFrame写入excel不同的sheet

      本文链接:https://www.haomeiwen.com/subject/mwtxwqtx.html