简体   繁体   English

数据框将数据框附加到带有工作表名称的excel?

[英]Dataframe append dataframe to excel with sheet names?

I desire to append multiple dataframes to a blank dataframe, and then export them to excel file with sheet name.我希望将多个数据框附加到一个空白数据框,然后将它们导出到带有工作表名称的 excel 文件。 I am stuck with it now.我现在被它困住了。 I simplify my code and look like this我简化了我的代码,看起来像这样


import pandas as pd
import numpy as np

def calculate_file():
    sheet_df = pd.DataFrame()
    for i in range(40):
#This is a toy dataframe
        random_data = np.random.randint(10,25,size=(5,3))
        df = pd.DataFrame(random_data, columns=['Column_1','Column_2','Column_3'])
    sheet_df = sheet_df.append(df)
    return(sheet_df)
calculate_file()

My desire output is dataframe with 40 sheet names exporting to an Excel file, and the name is Sheet1 to Sheet 40我想要的输出是具有 40 个工作表名称的数据框导出到 Excel 文件,名称是 Sheet1 到 Sheet 40

You need to save the sheet name somewhere, for instance in the index:您需要将工作表名称保存在某处,例如在索引中:

def calculate_file():
    sheet_df = pd.DataFrame()
    for i in range(1, 41):
        random_data = np.random.randint(10, 25, size=(5,3))
        df = pd.DataFrame(random_data,
                          columns=['Column_1', 'Column_2', 'Column_3'],
                          index=[f'Sheet {i}'] * len(random_data))
        sheet_df = pd.concat([sheet_df, df])
    return(sheet_df)

sheet_df = calculate_file()

Then you can use an ExcelWriter :然后你可以使用ExcelWriter

with pd.ExcelWriter('output.xlsx') as writer:
    for sheet in sheet_df.index.unique():
        sheet_df.loc[sheet].to_excel(writer, sheet, index=False) 

在此处输入图像描述

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

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