[英]Python - Iterate through excel column values to split up into separate sheets
I have an excel file with different columns, and I would like to split them up into different sheets based on unique column values (in this case, the month name. So 12 sheets would be created, one for each month. I got it working when I hardcoded it without loops, but I'd rather loop it through a list to save the time.我有一个包含不同列的 excel 文件,我想根据唯一的列值(在本例中为月份名称)将它们分成不同的工作表。因此将创建 12 个工作表,每个月一个。我让它工作当我在没有循环的情况下对其进行硬编码时,但我宁愿通过一个列表循环它以节省时间。
My current output in the excel file a sheetname called 'February' with the entire dataset.我当前在 excel 文件中的 output 文件名称为“February”,其中包含整个数据集。
Anyone have any ideas?有人有想法么? Thank you!
谢谢!
import xlrd
import xlsxwriter
df = pd.read_excel(r"PATH\data_test.xlsx", index_col = 0)
#writer = pd.ExcelWriter("Test3.xlsx", engine = 'xlsxwriter')
test_list = ['January', 'February']
for i in test_list:
writer = pd.ExcelWriter("Test3.xlsx", engine='xlsxwriter')
df.loc[i]
df.to_excel(writer, sheet_name = i)
print(i)
writer.save()
contents of df: df的内容:
Month Amount
January 125
January 32
February 12
March 70
April 48
May 98
June 110
July 7
August 124
September 63
October 93
November 6
December 118
something like this should work:像这样的东西应该工作:
groups = df.groupby("Month")
with pd.ExcelWriter("my_file.xls") as writer:
for (name, df_group) in groups:
df_group.to_excel(writer, sheet_name=name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.