Unable to export dataframe into separate excel files using pandas

Question:

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()
Asked By: Trevor M

||

Answers:

This will produce one separate Excel workbook:

df = pd.DataFrame([
    ['A',1],
    ['A',2],
    ['B',3],
    ['B',4],
    ['B',5]], columns=['id','val'])

data = df.groupby('id')

for group, frame in data:
    frame.to_excel(f"{group}.xlsx", index=False)  

Documentation:
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html

You don’t need to use the ExcelWriter for your use-case:

To write a single object to an Excel .xlsx file, it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to.

Answered By: lummers
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)
Answered By: user1889297
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.