python - 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)
我没有收到任何错误,但也没有收到新文件或写入现有文件。
解决方案
实际上,我相信这是一个更好的解决方案。用以下代码替换你的 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()
推荐阅读
- c# - .NET Core,随机创建重复记录
- typo3 - QueryBuilder lastInsertId()
- python - 如何修复浮点对象不能解释为整数python
- javascript - 从 Angular 7 组件中检索本地 XML 文件
- mysql - How to Sum Value's of a column in a Table using Lookup function
- asp.net-core - 如何解决 ASP.NET Core 2.0 应用程序 EF Core 使用中的大量内存分配问题?
- sql - 使用 Spark SQL 引擎为自定义库解析 SQL 所需的建议
- java - 我可以配置 Java 日志记录以使用 Spring Boot 日志记录吗?
- php - 无法使用 $GLOBALS 数组将变量从一个文件传递到另一个文件
- c - 无法弄清楚为什么我没有从一个线程获取作为输入的数组并尝试使用另一个线程打印它