DataFrame写入excel不同的sheet
直接上代码
初始化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() #高版本save会直接调用close() #write.close()
执行结果
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)