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.
My current output in the excel file a sheetname called 'February' with the entire dataset.
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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.