【问题标题】:Python Loop to write Dataframes to Excel Files if both the Dataframe and Excel File have the same name如果数据框和 Excel 文件具有相同的名称,则 Python 循环将数据框写入 Excel 文件
【发布时间】:2019-05-04 04:01:53
【问题描述】:

我有一个数据框字典,我想将其导出到存储在特定目录中的单个 excel 文件中。

我想设置一个 python 循环,将数据框(作为新工作表)导出到与数据框同名的 excel 文件中,并遍历每个数据框。

这是我目前所拥有的:

    multi_sheet_file = pd.ExcelFile(r'filename.xlsx')

    # Gets the sheet names in the file
    excel_sheet_names = multi_sheet_file.sheet_names

    dict_of_sheets = {}
    for sheet in excel_sheet_names:
        dict_of_sheets[sheet] = pd.read_excel(multi_sheet_file, 
    sheet_name=sheet)

如何设置 python 循环,将数据框导出到现有的同名 excel 文件?

【问题讨论】:

  • 那么您是否尝试为每个数据帧编写一个新文件?还是你想用多张纸写一个 excel 文件?
  • 到目前为止,你有什么问题?其实,你的问题是什么?
  • 我正在尝试将每个数据帧写入现有文件。因此,我的每个工作表名称都将对应于具有相同工作表名称的现有 excel 文件。我想遍历工作表名称(数据框)并将它们写入具有相同名称的 excel 文件。希望这不会太令人困惑。

标签: python dataframe export


【解决方案1】:

您应该能够遍历您的字典,其中的键是工作表名称:

for sheet, df in dict_of_sheets.items():
    df.to_excel('some_excel_file.xlsx', sheet_name=sheet)

我不确定这是否需要有序操作,但在 py3.6+ 中,如果重要的话,字典会根据键插入的顺序进行排序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多