I am trying to export a dataframe that I create in python to excel by group. I would like to create a new separate excel file for each group, not sheets within he same excel file.
This is the code I have right now and it creates sheets within the same excel file for each group. How can I alter this to create separate excel files. Do I need to write a for loop? Many of the solutions I am finding on Stack Overflow seem to be pointing in that direction.
data = df.groupby('ID')
writer = pd.ExcelWriter('Data_New.xlsx', engine='xlsxwriter')
for row,group in data:
group.to_excel(writer, index = None, sheet_name=row)
writer.save()
import pandas as pd
import numpy as np
#Example for DataFrame
df = pd.DataFrame(np.random.randint(0,4,size=(50, 4)), columns=['ID', 'A', 'B', 'C'])
# loop without groupby
for ID in df['ID'].unique():
df[df['ID']==ID].to_excel(f'C:/temp/ID_{ID}.xlsx', index=False)