首页 > 解决方案 > Python/Pandas:使用“for-loop”将多个数据框写入 Excel 工作表

问题描述

我无法想象这个问题之前没有被问过,但我无法在这里找到答案:我得到了一个 Excel 文件作为 Dataframe 并在上面使用了 Dataframe.groupby。现在我想为每个组使用不同的工作表将每个组保存到一个新的 Excel 文件中。我所能做的就是在每个文件中创建一个包含一组的新文件。我的新“解决方案”什么也没做。

df = pd.read_excel(file)
neurons = df.groupby("Tags")

#writing Keys into a list
tags = neurons.groups.keys()
tags = list(tags)


for keyInTags in tags:
     cells = group.get_group(keyInTags)
     cells.to_excel("final.xlsx", sheet_name=keyInTags)

我没有收到任何错误,但也没有收到新文件或写入现有文件。

标签: pythonexcelpandasdataframe

解决方案


实际上,我相信这是一个更好的解决方案。用以下代码替换你的 for 循环:

writer = pd.ExcelWriter('excel_file_name.xlsx')

for keyInTags in tags:
     cells = group.get_group(keyInTags)
     cells.to_excel(writer, sheet_name=keyInTags)

writer.save()
writer.close()

推荐阅读