[英]Python/Pandas: writing multiple Dataframes to Excel sheets using a “for-loop”
I cant imagine this question wasnt asked before but im not able to find the answere here: I got a Excel-File as Dataframe and used Dataframe.groupby on it. 我无法想象之前没有问过这个问题,但我无法在这里找到答案:我有一个Excel-File作为Dataframe并使用了Dataframe.groupby。 Now I want to save every single group into ONE new Excel file using a DIFFERENT Sheet for every Group.
现在,我想使用每个组的不同表格将每个组保存到一个新的Excel文件中。 All I was able to do is creating a lot new files with one group in every file.
我所能做的就是在每个文件中创建一个包含一个组的新文件。 My new "solution" does nothing.
我的新“解决方案”什么也没做。
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)
I get no errors but also not new file or writing to an existing file. 我没有错误,但也没有新文件或写入现有文件。
Actually, I believe this is a better solution. 实际上,我相信这是一个更好的解决方案。 Replace your for loop with this code:
用以下代码替换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()
Here is a cleaner solution for anyone still looking: 对于仍在寻找的人来说,这是一个更清洁的解
import pandas as pd
df = pd.read_excel("input.xlsx")
with pd.ExcelWriter("output.xlsx") as writer:
for name, group in df.groupby("column_name"):
group.to_excel(writer, index=False, sheet_name=name[:31])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.